hibernate annotation usage details

1. The class-level annotation
@Entity maps the entity class
@Table maps the database table 
@Entity(name="tableName") - Required, the annotation declares a class as an entity bean.
Attributes:
name - optional, corresponds to a table in the database. If the table name is the same as the entity class name, it can be omitted.
 
@Table(name="",catalog="",schema="") - optional, usually used in conjunction with @Entity, it can only be marked at the class definition of the entity, indicating the information of the database table corresponding to the entity.
Attributes:
name - optional, indicating the name of the table, by default, the table name and entity name are the same, only in the case of inconsistency need to specify the table name
catalog - optional, indicating the catalog name, the default is Catalog("").
schema - Optional, indicates the Schema name, the default is Schema(""). 2. Attribute-level annotation @Id mapping generates primary key @Version defines optimistic locking @Column mapping table column @Transient defines transient attribute   @Id related to primary key - Mandatory, defines the attribute that maps to the primary key of the database table. An entity can only have one attribute mapped to the primary key, which is placed before getXxxx().







 


 
@GeneratedValue(strategy=GenerationType,generator="") - optional, defines the primary key generation strategy.
Attributes:
Strategy - Indicates the primary key generation strategy, the values ​​are:
GenerationType.AUTO - Automatically selected according to the underlying database (default), if the database supports the automatic growth type, it will be automatic growth.
GenerationType.INDENTITY - Generated based on the Identity field of the database, supports the Identity type primary key of DB2, MySQL, MS, SQL Server, SyBase and HyperanoicSQL databases.
GenerationType.SEQUENCE - Use Sequence to determine the value of the primary key, suitable for Oracle, DB2 and other databases that support Sequence, generally used in conjunction with @SequenceGenerator.
(Oracle does not have an automatic growth type, only Sequence can be used)
GenerationType.TABLE - Use the specified table to determine the primary key value, combined with @TableGenerator.
For example:
@Id
@TableGenerator(name="tab_cat_gen",allocationSize=1)
@GeneratedValue(Strategy=GenerationType.Table)
Generator - Indicates the name of the primary key generator, this property is usually related to the ORM framework, for example:
Hibernate can specify the primary key generation method such as uuid
 
@SequenceGenerator - The annotation declares a database sequence.
Attributes:
name - Indicates the name of the primary key generation strategy for this table, which is referenced in the "gernerator" value set in @GeneratedValue.
sequenceName - Indicates the database sequence name used to generate the strategy.
initialValue - indicates the initial value of the primary key, the default is 0.
allocationSize - the size of the primary key value increase each time, for example, if set to 1, it means that it will automatically increase by 1 every time a new record is created, and the default is 50.
Example :
    @Id
    @GeneratedValues( strategy=StrategyType.SEQUENCE)
    public int getPk() {
       return pk;  
    } 
 
When Hibernate's access type is field, annotate the field;
when the access type is property, annotate and declare on the getter method.
 
2.2 Annotation @Version with non-primary keys
- @Version annotation can be used in entity beans to add support for optimistic locking
 
@Basic - used to declare the property's access strategy:
@Basic(fetch=FetchType.EAGER) immediate fetch (default access strategy)
@Basic(fetch=FetchType.LAZY) lazy fetch
 
@Temporal - used to define the mapping to the database The time precision of:
@Temporal(TemporalType=DATE) date
@Temporal(TemporalType=TIME) time
@Temporal(TemporalType=TIMESTAMP) both
 
@Column - properties can be mapped to columns, use this annotation to override defaults, @ Column describes the detailed definition of the field in the database table, which is very useful for tools that generate database table structure based on JPA annotations.
Attributes:
name - optional, indicating the name of the field in the database table, the default case attribute name is the same
nullable - optional, indicating whether the field is allowed to be null, the default is true
unique - optional, indicating whether the field is a unique identifier, The default is false
length - optional, indicating the size of the field, only valid for fields of type String, the default value is 255.
insertable - optional, indicating whether the field should appear in the INSETRT statement when the ORM framework performs an insert operation, the default true
updateable - optional, indicating whether the field should appear in the UPDATE statement when the ORM framework performs an update operation, the default is true. This property is useful for fields that cannot be changed once created, such as the birthday field.
columnDefinition - optional, indicating the actual type of the field in the database. Usually the ORM framework can automatically determine the type of the field in the database according to the attribute type, but it still cannot determine whether the field type in the database is DATE, TIME or TIMESTAMP for the Date type. In addition, the default mapping type of String is VARCHAR, if you want to map the String type This property is useful for BLOB or TEXT field types to a specific database.
Example :
    @Column(name="BIRTH",nullable="false",columnDefinition="DATE")
    public String getBithday() {
       return birthday;
    }
  
@Transient - optional, indicating that the property is not a field to the database table Mapping, the ORM framework will ignore this attribute. If an attribute is not a field mapping of the database table, it must be marked as @Transient, otherwise the ORM framework defaults to its annotation as @Basic
Example:
    // Calculate the age attribute based on birth
    @Transient
    public int getAge() {
       return getYear(new Date()) - getYear(birth);
    }
2.3 The default value
of an unannotated attribute If the attribute is a single type, it is mapped to @Basic,
otherwise, if the type corresponding to the attribute defines the @Embeddable annotation, it is mapped to @Embedded,
otherwise, if the type corresponding to the attribute implements Serializable, the attribute is mapped to @Basic and stores the serialized version of the object in a column,
otherwise, if the type of the attribute is java.sql.Clob or java.sql .Blob, then as @Lob and mapped to the appropriate LobType. 3. Mapping the inheritance relationship @Inheritance annotation to define the selected strategy. This annotation needs to be used on the topmost entity class of each class hierarchy 4. Mapping the association relationship of entity beans 4.1 Some definitions of association mapping To one-to-many: one party has a collection property, including multiple many parties, and the many parties do not have a reference to one party. User--->Email One- way many-to-one: Many parties have a reference to one party, and one party does not have a reference to many parties. Paper Category---> Category Bidirectional one-to-many: There are multiple references on both sides, which is convenient for query. Class--->Student Two- way many-to-one: There are multiple references on both sides, which is convenient for query. One-way many-to-many: An intermediate table is required to maintain two entity tables. Forum--->Article One -to-one: The data is unique, and the database data is also one-to-one. Ship ---> Sailor One-to-one with the same primary key: use the same primary key, omitting foreign key associations. Client--->Address

 













 
One-way: Where the relationship is written, whoever manages it.
Bidirectional: Generally managed by multiple parties.
@OneToMany(mappedBy="the other party") //Reverse configuration, the other party manages.
4.2 Some Common Attributes of Association Mapping
Common attributes of @OneToOne, @OneToMany, @ManyToOne, ManyToMany:
fetch - configure the loading method. The values ​​are
Fetch.EAGER - load in time, many-to-one default is Fetch.EAGER 
Fetch.LAZY - lazy loading, one-to-many default is Fetch.LAZY
cascade - set cascade mode, the values ​​are:
CascadeType.PERSIST - save
CascadeType .REMOVE - Delete
CascadeType.MERGE - Modify
CascadeType.REFRESH - Refresh
CascadeType.ALL - All
targetEntity - Configure collection property types, such as: @OneToMany(targetEntity=Book.class) @JoinColumn
 
- optional, used to describe an associated field .
@JoinColumn is similar to @Column, the mediator describes not a simple field, but an associated field, such as a field describing a @ManyToOne.
 
Attributes:
name - the name of the field. Since @JoinColumn describes an associated field, such as ManyToOne, the default name is determined by its associated entity.
For example, the entity Order has a user attribute to associate the entity User, then the user attribute of the Order is a foreign key, and
its default name is the name of the entity User + underscore + the primary key name of the entity User
4.3 One-to-one association
@OneToOne – represents a One-to-one mapping
1. The primary table class A corresponds to the primary key value of the secondary table class B.
 Primary table: @OneToOne(cascade = CascadeType.ALL)
     @PrimaryKeyJoinColumn
     public B getB(){
  Return b;
    } Secondary
table: None
 

2. There is a secondary table in primary table A whose attribute is type B.
Primary table: @OneToOne( cascade = CascadeType.ALL)
   @JoinColumn(name="primary table foreign key") //The foreign key field in the database is specified here. public B
   getB(){
return b;
       }
Slave: none @OneToOne(cascade = CascadeType.ALL)
 



   @JoinColumn(name="primary table foreign key") //The foreign key field in the database is specified here.
   public B getB(){
return b;
       }
Slave table: @OneToOne(mappedBy = "Slave table attribute in the main table class")
   public main table class get main table class(){
return main table object
      }
  Note: @JoinColumn is optional. The default value is the variable name of the slave table + "_" + the primary key of the slave table (note that the primary key is added here. Instead of the variable corresponding to the primary key).


4.4 Many-to-One Association
@ManyToOne - Represents a many-to-one mapping, and the attribute marked by this annotation is usually the foreign key of the database table.
1. One-way many-to-one: Many parties have a reference to one party, and one party does not have a reference to multiple parties.
           In the multi-party
@ManyToOne(targetEntity=XXXX.class) //Specify the associated object
@JoinColumn(name="") //Specify the generated foreign key field name


 
2. Two-way many-to-one: The configuration method is the same as two-way one-to-many.
 
Example:
    // Order Order and User User are a ManyToOne relationship // define     @ManyToOne()
    in the Order class

    @JoinColumn(name="USER")
    public User getUser() {
       return user;
}


4.5 One-to-many association
@OneToMany - describe a one-to-many association, the attribute should be a collection type, and there is no actual field in the database.
1. One-way one-to-many: one party has a set attribute, including multiple parties, and the multiple parties do not have a reference to one party.
@OneToMany will use the join table for one-to-many association by default. After
adding @JoinColumn(name="xxx_id"), the foreign key association will be used instead of the join table.
 
 2. Two-way one-to-many
1)
@ManyToOne @JoinColumn
(name="your own database foreign key column name")

2)
@OneToMany(mappedBy="multi-terminal associated attribute name")
@JoinColumn(name=" The database foreign key column name of the other party")

4.6 Many-to-many association
@ManyToMany - Optional, describe a many-to-many association.
Attributes:
targetEntity - the full name of another entity class representing a many-to-many association, for example: package.Book.class
mappedBy - used in a bidirectional association to reverse the maintenance right of the relationship.
 
1.

2. Bidirectional many-to-many association:
    The attributes associated with each other between two entities must be marked as @ManyToMany, and the targetEntity attribute must be specified to each other. The @ManyToMany annotation with one and only one entity needs to specify the mappedBy property, pointing to the collection property name of the targetEntity.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327091495&siteId=291194637