Use of Hibernate annotations

Keywords: Database Hibernate xml Attribute

In Hibernate, there are usually two ways to configure object-relational mapping, one is based on xml, the other is based on annotation of Hibernate Annotation library. In Hibernate version 3.2 and Java 5 environment, annotations are used to configure object-relational mapping. After using Hibernate annotations, the *.hbm.xml file corresponding to the persistent class can be written directly into the persistent class by annotations instead of defining the corresponding *.hbm.xml file.

Two differences between the two methods should be noted:
(1): In the hibernate.hbm.xml file, change the reference: x xxx.hbm.xml to the reference entity class:

That is to say, <mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/>
Replace with: <mapping class="com.wsw.hibernate.model.Teacher"/>

(2): The way to obtain SessionFactory has changed:

That is, SessionFactorysf = new Configuration (). configure (). buildSessionFactory ()
Change to SessionFactory SF = new Annotation Configuration (). configure (). buildSessionFactory ()

Commonly used annotation labels

In the use of attribute annotations, you can maintain the persistence of both fields (annotations are written on member variables) and attributes (annotations are written on getter methods), but it is recommended not to introduce annotations on attributes, because attributes are private, if the introduction of annotations will destroy their encapsulation characteristics, so it is recommended that Add annotations to the getter method

@Entity

It is best to declare a Java bean class as an entity's database table mapping class. By default, all class attributes are persistent fields mapped to data tables. If there are attributes in the class that are not mapped to the database, annotate them with @Transient below.
Attributes:
Name - optional, corresponding to a table in the database. If the table name is the same as the entity class name, it can be omitted.

@Table

Used under @Entity to represent information about tables in an entity's corresponding database
Attributes:
Name - optional, indicating the name of the table, default table name and entity name consistent, inconsistent cases need to specify the table name.
Catalog - optional, denoting the Catalog name, defaulting to Catalog("")
Schema - optional, indicating the name of Schema, defaulting to Schema("")

@Entity()
@Table(name="Student")
public class Student implements Serializable{
}

@Id

It is necessary to define the attributes of the primary key mapped to the database table. Only one attribute of an entity can be mapped to the primary key.

@GeneratedValue

Define the generation strategy of auto-growing primary keys.
Attributes:
Strategy - Represents the primary key generation strategy with the following values

GenerationType.AUTO According to the underlying database automatic selection (default), if the database supports automatic growth > type, it is automatic growth.
GenerationType.INDENTITY Support Identity of DB2, MySQL, MS, SQL Server, SyBase and Hyperanoic SQL database by generating Identity field of database
GenerationType.SEQUENCE The use of Sequence to determine the value of the primary key is suitable for Oracle, DB2 and other databases that support Sequence, generally combined with @SequenceGenerator. (Oracle has no automatic growth type and can only use Sequence)
GenerationType.TABLE Use the specified table to determine the primary key value and use it in conjunction with @TableGenerator.
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY) 
private int sid;

Use of GenerationType.TABLE

@Id  
@GeneratedValue(strategy=GenerationType.TABLE,generator="strategyName")   
@TableGenerator(
    name = "strategyName",   // The name of the primary key generation policy, which is referenced in the "generator" value set in @GeneratedValue
    table="",   //Represents the table name persisted by the table generation strategy   
    catalog="",   //The directory name of the table
    schema="",   //Database name
    pkColumnName="",   //In the persistence table, the name of the key value corresponding to the primary key generation policy
    valueColumnName="",   //Represents the value currently generated by the primary key in the persistence table, whose value will accumulate with each creation  
    pkColumnValue="",   //Represents the primary key corresponding to this generation strategy in the persistence table  
    allocationSize=1   //Indicates the size of each increase in the primary key value, for example, set to 1, which automatically adds 1 after each creation of a new record. The default is 50.
)  

Use of Generation Type.SEQUENCE

@Id  
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="strategyName")   
@SequenceGenerator(
    name="strategyName", //The name attribute represents the name of the table's primary key generation policy, which is referenced in the "generator" value set in @GeneratedValue
    sequenceName=""  //Represents the name of the database sequence used for the generation policy
) 

More annotation-based Hibernate primary key generation strategies

@Transient

These fields and attributes will be ignored without persistence to the database.

@Column

You can map attributes to columns and use this annotation to override default values
Attributes:
Name-optional, indicating the name of the field in the database table, and the default attribute name is the same
length - Optional, indicating the size of the field, only valid for String type fields, default value 255.
insertable - optional, indicating whether the field should appear in the INSETRT statement when the ORM framework performs the insert operation, defaulting to true
updateable - optional, indicating whether the field should appear in the UPDATE statement when the ORM framework performs an update operation, defaulting to true. This property is very useful for fields that cannot be changed once created, such as the birthday field.
columnDefinition - Optional to indicate the actual type of field in the database. Often ORM frameworks can automatically determine the type of field in a database based on the attribute type, but it is still impossible to determine whether the field type in a database is DATE,TIME or TIMESTAMP. In addition, the default mapping type of String is VARCHAR, if the String type is mapped to a BLOB or T of a specific database. EXT field type, which is very useful.

@Version

Statement adds support for optimistic locking

Some attributes

fetch

Relation acquisition, i.e. whether to use delayed loading or not
Fetch. EAGER - Loading in time is to query data, but also directly together to obtain the data of related objects. Many-to-one default is Fetch.EAGER
Fetch.LAZY - Delayed loading. When querying data, the data of related objects are not queried together. It triggers the corresponding query operation when accessing the related object, and obtains the data of the related object. One-to-many defaults are Fetch.LAZY

cascade

Setting up cascade mode
CascadeType.PERSIST Save
CascadeType.REMOVE - Delete
Modification of CascadeType.MERGE
CascadeType.REFRESH refresh
CascadeType.ALL - All

mappedBy

mappedBy refers to the attributes of many-to-one dependencies. (Note: If we do not specify who will maintain the relationship, the system will create an intermediate table for us.)
If this one-to-many relationship is not maintained through the third table, but the id of one party is saved by many parties (multi-foreign key refers to one party), then mappedBy must be used to specify which variable in many parties is saved by one party (foreign key). The value is the attribute name of one party in many parties.
When deciding who maintains the association, you can look at the foreign key, which entity class defines the foreign key, and which class is responsible for maintaining the association.
mappedBy is equivalent to inverse="true" in xml configuration

One-to-many Association

@OneToMany

Describes a one-to-many association, which should be set type @OneToMany by default uses join tables for one-to-many associations
If this one-to-many relationship is not maintained through the third table, but the id of one party is saved by many parties (multi-foreign key refers to one party), then mappedBy must be used to specify which variable in many parties is saved by one party (foreign key). The value is the attribute name of one party in many parties.

@OneToMany(cascade={CascadeType.ALL},mappedBy="grade")
    public Set<Student> getStudents() {
        return students;
    }

Many-to-one Association

@ManyToOne

Represents a many-to-one mapping whose annotated attributes are usually foreign keys to database tables. One-way, many-to-one associations are multiple:
@ ManyToOne(targetEntity=XXXX.class) // / Specify the associated object
@ JoinColumn(name="")// Specifies the name of the foreign key field generated

Bidirectional one-to-many and bidirectional many-to-one

In many ways
@ManyToOne
@ JoinColumn(name = "own database foreign key column name")
On one side
@ OneToMany(mappedBy= "Multiplex Associated Property Name")

/*
 * Student Responsibility Association
 */
@Entity
@Table(name="Student")
public class Student implements Serializable{
    private int sid;
    private String sex;
    private String name;
    private Grade grade;
    public Student() {

    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Id
    @GenericGenerator(name="generator",strategy="native")
    @GeneratedValue(generator="generator")
    public int getId() {
        return sid;
    }
    public void setId(int id) {
        this.sid = id;
    }
    @Column(name="sex")
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="gid")
    public Grade getGrade() {
        return grade;
    }
    public void setGrade(Grade grade) {
        this.grade = grade;
    }
}
/*
 * Class Class
 */
@Entity
@Table(name="Grade")
public class Grade implements Serializable{
    private int gid;
    private String name;
    private Set<Student> students=new HashSet<Student>();
    public Grade() {
    }
    @Id
    @GenericGenerator(name="generator",strategy="native")
    @GeneratedValue(generator="generator")
    public int getGid() {
        return gid;
    }
    public void setGid(int gid) {
        this.gid = gid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @OneToMany(cascade={CascadeType.ALL},mappedBy="grade")
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }
}

Many-to-many Association

In many-to-many associations, both sides adopt @ManyToMany. The maintained party mappedBy means that it is maintained by another party.
Maintaining association by any party through intermediate tables
Instead of using @join Column as a pair of multi-annotations, the main control party uses @join Table.

 @JoinTable(
     name="student_course",
     joinColumns={@JoinColumn(name="")},
     inverseJoinColumns={@JoinColumn(name="")}
)

Because many-to-many will maintain a direct relationship between the two tables through an intermediate table, it is declared through the JoinTable annotation.
Name is the name of the intermediate table specified.
JoinColumns is an array of @JoinColumn type, representing the name of the foreign key in the other party, which is the primary key of the current class.
Inverse JoinColumns is also an array of @JoinColumn type, representing the foreign key name of the other party in our side. You can also think of it as follows: the mappedBy mentioned above is equivalent to inverse="true". Therefore, the field defined in inverse JoinColumns in @joinTable is the primary key of the class mappedBy belongs to.

On the basis of the former, we should add courses and supplement students'classes.

/*
 * Student Responsibility Association
 */
@Entity
@Table(name="Student")
public class Student implements Serializable{
    private int sid;
    private String name;
    private String sex;
    private Grade grade;
    private Set<Course> courses=new HashSet<Course>();
    public Student() {

    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Id
    @GenericGenerator(name="generator",strategy="native")
    @GeneratedValue(generator="generator")
    public int getId() {
        return sid;
    }
    public void setId(int id) {
        this.sid = id;
    }
    @Column(name="sex")
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="gid")
    public Grade getGrade() {
        return grade;
    }
    public void setGrade(Grade grade) {
        this.grade = grade;
    }
    @ManyToMany(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
    @JoinTable(name="student_course",joinColumns={@JoinColumn(name="sid")},inverseJoinColumns={@JoinColumn(name="cid")})
    public Set<Course> getCourses() {
        return courses;
    }
    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
}
@Entity
@Table(name="Course")
public class Course implements Serializable{

    private int cid;
    private String cName;
    private Set<Student> students=new HashSet<Student>();
    public Course() {
    }
    @Id
    @GenericGenerator(name="generator",strategy="native")
    @GeneratedValue(generator="generator")
    public int getCid() {
        return cid;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }
    public void setCid(int cid) {
        this.cid = cid;
    }
    public String getcName() {
        return cName;
    }
    public void setcName(String cName) {
        this.cName = cName;
    }
    @ManyToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY ,mappedBy="courses") 
    public Set<Student> getStudents() {
        return students;
    }
}

Posted by perrio on Sun, 07 Jul 2019 13:25:48 -0700