Hibernate annotations

Hibernate4 Annotation Method
_ _ _ (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 if they are inconsistent, you 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  2.1 Annotation related to primary key




















@Id - Required, defines the property that maps to the primary key of the database table, an entity can only have one property that is mapped to the primary key, 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 is 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.
eg:
@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 Notes on non-primary keys
@Version - can be annotated with @Version in entity beans to add support for optimistic locking in this way @Basic

- used to declare access strategy for properties:
@Basic(fetch=FetchType.EAGER) Instant fetch (default access policy)
@Basic(fetch=FetchType.LAZY) Lazy fetch

@Temporal - used to define the time precision mapped to the database:
@Temporal(TemporalType=DATE) date
@Temporal(TemporalType=TIME) time
@Temporal(TemporalType=TIMESTAMP ) Both

@Column - can map properties to columns, use this annotation to override the default value, @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, defaults to 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 a 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 Default value of unannotated attribute
If 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 the collection property type, 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:
    // The relationship between order Order and user User is a ManyToOne // 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. One-way many-to-many association:
    Add the @ManyToMany annotation to the main controller.
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.
[From:blog_935ebb670101dnre.html]

@Entity, registered on the class header, declares a class as an entity bean (ie, a persistent POJO class).
@Table, registered on the class header, the annotation declares the table (table) specified by the entity bean mapping.
@Id is used to register the main property, @GeneratedValue is used to register the generation strategy of the main property, @Column is used to register the property, @Version is used to register the optimistic lock, and @Transient is used to register the non-property.
The above @Id, @GeneratedValue, @Column and @Version can be used to register properties, which can be written on the properties of Java classes or registered on the getters corresponding to the properties.
@Transient is registered on redundant properties or redundant getters, but must correspond to @Column etc. above.
@Column
identifies the field corresponding to the attribute, example: @Column(name="userName")

@Column(
    name="columnName"; (1)
    (2)
    boolean nullable() default true; (3)
    boolean insertable() default true; (4)
    boolean updatable() default true; (5)
    String columnDefinition() default ""; (6 )
    String table() default ""; (7)
    int length() default 255; (8)
    int precision() default 0; // decimal precision (9)
    int scale() default 0; // decimal scale (10)
(1) name is optional, the column name (the default value is the attribute name)
(2) unique is optional, whether to set a unique constraint on the column (the default value is false)
(3) nullable is optional, whether to set the value of the column can be Empty (default value false)
(4) insertable optional, whether the column is used as a column in the generated insert statement (default value true)
(5) updatable Optional, whether the column is used as a column in the generated update statement (default value is true)
(6) columnDefinition Optional: override the SQL DDL fragment for this specific column (this may lead to inability to portability between different databases)
(7) table is optional, define the corresponding table (the default is the main table)
(8) length is optional, the length of the column (the default value is 255)
(8) precision is optional, the decimal precision of the column (the default value is 0)
(10) scale is optional, if the column decimal scale is available, set here (default value 0)
@Id, which identifies this property as the unique value of the entity class.
Note: This annotation can only mark the primary key composed of a single column, such as tbl_grade, a joint primary key composed of two fields is identified by other annotations.
Recall *.hbm.xml:
"uuid">
"assigned"/>
      
@Id, just identifies this attribute as the primary key, but does not indicate its generation strategy. As in the above example, assigned is the generation strategy specified by the programmer.
If you just write out @Id, you are using assigned generation, such as:
@Id
@Column
private int uuid;
if you want to use the sequence supported by Oracle to get the primary key, you must specify the generation strategy through @GeneratedValue, and @SequenceGenerator specifies how to use sequence.
@Id
@Column
@GeneratedValue(
strategy = GenerationType.SEQUENCE,//Use sequence to generate the primary key
generator = "generator"//Refer to the generation strategy named gernator below
)
@SequenceGenerator( name = "generator",//Define the generation strategy allocationSize
named generator
= 1, //Add 1 to each sequence
name="seq_a"//Refer to the sequence named seq_a
)
private int uuid;
@Version
identifies the version of this attribute used to map optimistic locks
@Transient
identifies that this attribute does not need to be persisted
@Embeddable [On the head of the small object]
An embedded component can be defined in the identified entity. Component classes must define the @Embeddable annotation at the class level.
@Embedded [on the property header of the large object]
refers to the defined small object.
@Embeddable [on the head of the small object]
identifies that an embedded component can be defined in the entity. Component classes must define the @Embeddable annotation at the class level.
Note: If this small object is used as a composite primary key, be sure to implement the Serializable interface. This is not doomed, but Hibernate's primary key needs to implement the Serializable interface.
@EmbeddedId [on the property header of the large object]
refers to the defined small object as the primary key.
Note: No need to use the @Id annotation anymore.
 
Standard 1:1
Hibernate4 annotation method

XML configuration
master 1 [tbl_product]:

slave 1 [tbl_product_info]:


product [reference own Java property name]


configuration of annotation
master 1 [tbl_product]:
@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
private ProductInfoModel info;
from 1[tbl_product_info]:
@Id
@Column
@GeneratedValue(generator="copy[reference generation strategy]")
@GenericGenerator(name="copy[definition generation strategy]", strategy="foreign[write Die, use foreign strategy]",parameters=@Parameter(name="property",value="product[reference own Java property]"))
private int uuid;
@OneToOne(mappedBy=”info [reference the Java property of the other party]”)
private ProductModel product;

Standard 1:M
 
XML configuration
1 [tbl_parent]:

      
      

Multiple [tbl_child]:
Annotation configuration

1 [tbl_parent]:
@OneToMany @JoinColumn
(name="puuid[the other party's database foreign key column name]")
private Set children = new HashSet();
Multiple [tbl_child]:
@ManyToOne @JoinColumn
(name="puuid[own database foreign key column ] Name]")
private ParentModel parent;
Hibernate4 annotation method

Master   1[tbl_product]:
" cascade="all"/>  
Slave 1[tbl_product_info]:  
true[Write dead]"/> 
Annotation configuration
Master 1[tbl_product]:
@OneToOne (cascade=CascadeType.ALL, mappedBy="product [the Java class attribute name of the other party]")
private ProductInfoModel info;
From 1[tbl_product_info]:
@OneToOne @JoinColumn
(name="puuid[own database foreign key column name]")
private ProductModel product;
Hibernate4 annotation method

XML configuration
1[tbl_parent]:

      
      
class="cn. javass.model.d.ChildModel[the other party's Java class name]"/>
      

      
      
Annotation configuration
1[tbl_parent]:  
@OneToMany(mappedBy="parent[the other party's Java class attribute name]")  
private Set children = new HashSet() ;  
Multiple [tbl_child]:  
@ManyToOne 
@JoinTable(  
name="tbl_parent_child[join table]",  
joinColumns=@JoinColumn(name="cuuid[name of database field in the join table]"),  
inverseJoinColumns=@JoinColumn(name ="puuid [database field name representing the other party in the join table]")  
)  
private ParentModel parent;   
Hibernate4 annotation method

XML configuration
1 [tbl_product]:

      
      

Annotation configuration
1 [tbl_product]:
@ManyToOne
@JoinTable(
name=" tbl_product_relation [join table]",
joinColumns=@JoinColumn(name="suuid [represents its own in the join table Column name]"),
inverseJoinColumns=@JoinColumn(name="cuuid[the column name representing the other party in the join table]",unique=true[write dead])
)
private CourseModel course;

[From: http://sishuok.com /forum/blogPost/insert.html]

Error 1
Error message: javax.persistence.Table.indexes([Ljavax/persistence/Index
Reason: Hibernate4.3 does not support @table(name="tablename")
Solution: use @entity (name="tablename") instead of @table(name="tablename")

Error 2
Error message: javax.persistence.JoinColumn.foreignKey()Ljavax/persistence/ForeignKey
Reason: Hibernate 4.3 cannot use @JoinColumn in many-to-one mapping
Solution: write only @ManyToOne

Error three
Error message: javax.persistence.OneToMany.orphanRemoval()Z
Reason: javaee, ejb or junit jar package and hibernate -jpa-2.0-api-1.0.0.Final.jar conflict
Solution : Check whether the above jar package exists, if so, remove it

Guess you like

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