Hibernate implements a ing relationship between entities and databases based on Annotation configuration.
There is a ing between entities and databases. hibernate completes data access based on this ing. In the program, this ing relationship is defined by the ing file (*. hbm. xml) or java annotation.
This article summarizes the ing relationship configuration in the form of java annotations.
1. import dependency packages.
Hibernate-distribution-3.6.5.Final-dist \ hibernate-distribution-3.6.5.Final \ lib \ hibernate-jpa-2.0-api-1.0.0.Final.jar under jpa directory
Ii. Create an object class
Package com. souvc. domain. user; import java. util. date; import javax. persistence. cascadeType; import javax. persistence. column; import javax. persistence. entity; import javax. persistence. generatedValue; import javax. persistence. generationType; import javax. persistence. id; import javax. persistence. joinColumn; import javax. persistence. manyToOne; import javax. persistence. table; import javax. persistence. temporal; import javax. persistence. temporalType; import org. springframework. format. annotation. dateTimeFormat;/*** Class Name: UserLoginLog * Description: User Logon record table class * developer: souvc * Creation Time: 2015-9-7 * @ version V3.0 */@ Entity @ Table (name = "user_login_log") public class UserLoginLog implements java. io. serializable {private static final long serialVersionUID = 8686390425132322570l; private Integer loginId; private String ip; private String address; private Integer type; private Integer status; @ DateTimeFormat (pattern = "yyyy-MM-dd HH: mm: ss") private Date loginTime; // private UserBaseInfo userBaseInfo; @ Id @ GeneratedValue (strategy = GenerationType. IDENTITY) @ Column (name = "login_id", unique = true, nullable = false) public Integer getLoginId () {return loginId;} public void setLoginId (Integer loginId) {this. loginId = loginId;} @ Column (name = "ip", nullable = true) public String getIp () {return ip;} public void setIp (String ip) {this. ip = ip ;}@ Column (name = "address", nullable = true) public String getAddress () {return address;} public void setAddress (String address) {this. address = address ;}@ Column (name = "type", nullable = false) public Integer getType () {return type;} public void setType (Integer type) {this. type = type ;}@ Column (name = "status", nullable = false) public Integer getStatus () {return status;} public void setStatus (Integer status) {this. status = status ;}@ Column (name = "login_time", nullable = true) @ Temporal (TemporalType. TIMESTAMP) public Date getLoginTime () {return loginTime;} public void setLoginTime (Date loginTime) {this. loginTime = loginTime;} // @ ManyToOne (cascade = CascadeType. REFRESH, optional = false) // @ JoinColumn (name = "user_id", unique = true) // public UserBaseInfo getUserBaseInfo () {// return userBaseInfo; ///} // public void setUserBaseInfo (UserBaseInfo userBaseInfo) {// this. userBaseInfo = userBaseInfo ;//}}View Code
Iii. Explanation
Object components and annotation label ing relationships
Entity class ----------- @ Entity/@ Table ---------- data Table
Id -------------- @ Id ---------- primary key
Common attributes --------- @ Column ---------- common keys
Set property --------- @ OneToMany/@ ManyToOne/@ ManyToMany/@ OneToOne ---------- foreign key
A. Before the class declaration:
A. @ Entity to indicate that this Bean is EntityBean. Every persistent POJO class is an entity bean, which can be used in the class definition@ EntityAnnotations.
B. @ Table (name = "TableName") indicates the name of the database Table corresponding to the object Bean.@ TableIs a Class-level annotation, through@ TableAnnotations can specify the names of tables, directories, and schemas for object bean ing.@ TableThe system automatically uses the default value: short class name of the object (excluding the package name ).@ TableThe element includesSchemaAnd oneCatalogAttribute. You can specify the value if needed.@ UniqueConstraintAnnotation can define the unique constraints of a table (unique constraint)
B. The statements written before the getXxx () method declaration are as follows:
A. @ Column Comment defines all attributes mapped to a Column, such as whether the Column name is unique, whether it is allowed to be empty, and whether update is allowed. Its Attributes are described as follows:
(1) name (optional) column name (default value: attribute name) (2) unique (optional) whether to set unique constraints (default value: false) (3) nullable (optional, whether to set the value of this column to null (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 true) (6) columnDefinition (optional) overwrite the SQL DDL segment for this specific column (this may cause migration between different databases) (7) table (optional) define the corresponding table (the main table by default) (8) length (optional), column length (default 255) (8) precision (optional), column decimal precision (decimal precision) (default value 0) (10) scale (optional) if the column's decimal value range (decimal scale) is available, set here (default value 0)
B. @ Id annotation specifies the personid attribute as the primary key of the table, which can be generated in multiple ways:
· TABLE: Containers use the underlying data TABLE to ensure uniqueness. · SEQUENCE: Use the SEQUENCE column of the database to ensure unique. IDENTITY: Use the INDENTIT column of the database to ensure unique. AUTO: The container selects an appropriate method to ensure unique. NONE: the container is not responsible for generating the primary key, which is completed by the calling program.View Code
C. @ GeneratedValue annotation defines how the ID field is generated.
D. @ Version ing Version attributes
E. @ Column specifies the Column information corresponding to the attribute
F. @ Temporal specifies the DATE and TIME type (TIMESTAMP, DATE, TIME)
G. Simple attributes do not need annotations. The default value is @ Basic.
H. @ Transient the specified attribute does not need to be mapped.
I. Complex attributes: Association, inheritance, component, joint primary key, Set
C. Relationship/object ing
A. one-to-many:
@ Onetoworkflow indicates that the link is a one-to-multiple link. The attributes of @ onetoworkflow annotation are as follows:
1> targetEntity
Class type attribute. Define the type of a link class. The default type is the class type corresponding to the member property. Therefore, definitions are not required.
2> mappedBy
String type attribute. Defines the bidirectional relationship between classes. If there is a unidirectional relationship between classes, no definition is required. If there is a bidirectional relationship between classes, we need to use this attribute for definition. Otherwise, Data Consistency may occur.
3> cascade
CascadeType [] type.
This attribute defines the cascade relationship between classes. The defined cascade relationship is considered by the container to take the same action on the current class object and its associated class object, and this relationship is called recursively.
For example, if Order and OrderItem have cascade relationships, the corresponding OrderItem object will be deleted when Order is deleted. If OrderItem has a cascade relationship with other objects, this operation will continue recursively.
The cascade value can only be from:
CascadeType. PERSIST (cascade new );
CascadeType. REMOVE (cascade delete );
CascadeType. REFRESH (cascade REFRESH );
Select one or more CascadeType. MERGE (cascade update.
Another option is CascadeType. ALL, which indicates that ALL four items are selected.
4> fatch
Properties of the FetchType type.
Optional items include FetchType. EAGER and FetchType. LAZY.
The former indicates that the relational class (in this example, the OrderItem class) is loaded simultaneously when the main class (in this example, the Order class) is loaded;
The latter indicates that the link class is loaded only when it is accessed. The default value is FetchType. LAZY.
@ OrderBy (value = "id ASC") annotation indicates that OrderItem is loaded in ascending order of id.
B. Many-to-one:
@ ManyToOne annotation, which has four attributes: targetEntity, cascade, fetch, and optional.
The meanings of the first three attributes are the same as those of the @ onetoworkflow Annotation with the same name. However, the default fetch attribute of the @ ManyToOne annotation is FetchType. EAGER.
The optional attribute defines whether the association class pair must exist. If the value is false, both parties of the association class must exist. If the maintenance end of the relationship does not exist, the query result is null. If the value is true, the link maintenance end may not exist, and the query result will still return the link maintenance end. In the relationship maintenance end, the attribute pointing to the link maintenance end is null.
The default value of the optional attribute is true.
For example, there is no OrderItem in an Order. If the optional attribute is set to false, when the Order is obtained, the result is null, if the optional attribute is set to true, the order can still be obtained, but the attribute pointing to the order item in the order is null.
In fact, when the relationship between Order and OrderItem is interpreted as SQL, the optional attribute specifies their join relationship.
Optional = false join link is inner join,
Optional = true join is left join.
@ JoinColumn (name = "order_id") specifies the order_id column of the OrderItem ing table as the foreign key and the primary key column of the Order ing table.
C. One-to-one:
The @ OneToOne annotation has five attributes: targetEntity, cascade, fetch, optional, and mappedBy.
The meanings of the first four attributes correspond to the attributes with the same name as the @ ManyToOne annotation. The default value of the fetch attribute is FetchType. EAGER.
The specific meaning of the mappedBy attribute is the same as that of the @ onetoworkflow annotation.
If optional = true, this attribute can be null.
For example, you can set the ID card in this way, because the minor does not have an ID card.
D. many to many:
@ ManyToMany note: this class is one side of the many-to-many relationship. The mappedBy attribute defines this class as the maintenance end of the bidirectional relationship. Note: the value of the mappedBy attribute is the attribute name at the other end of the link.
For example, the Student class has the following methods:
@ManyToMany(mappedBy = "students") public Set<Teacher> getTeachers() { return teachers;}
The "students" here is an attribute of Teachers, which is usually like this:
Set <Student> students;
The getStudents method on the other end is as follows:
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)@JoinTable(name = "Teacher_Student",joinColumns = {@JoinColumn(name = "Teacher_ID", referencedColumnName = "teacherid")},inverseJoinColumns = {@JoinColumn(name = "Student_ID", referencedColumnName ="studentid")})public Set<Student> getStudents() { return students;}
@ ManyToMany the comment indicates that Teacher is the end of the many-to-many relationship.
@ JoinTable describes the relationship between multiple-to-multiple data tables.
The name attribute specifies the name of the intermediate table. joinColumns defines the foreign key relationship between the intermediate table and the Teacher table.
In the code above, the Teacher_ID column of the middle table Teacher_Student is the foreign key column corresponding to the primary key column of the Teacher table. The inverseJoinColumns attribute defines the foreign key relationship between the middle table and the other end (Student.
Can refer to the Chinese official documentation: http://docs.jboss.org/hibernate/annotations/3.4/reference/zh_cn/html_single/