Hibernate implements a ing relationship between entities and databases based on Annotation configuration.

Source: Internet
Author: User

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. 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 ;//}}

 

Iii. Description of object components and annotation label ing relationship object classes ----------- @ Entity/@ Table ---------- data Table Id -------------- @ Id ---------- primary key common attributes --------- @ Column ---------- common key set attributes --------- @ OneToMany/@ ManyToOne/@ ManyToMany/@ OneToOne ---------- foreign key. before the class Declaration:. @ Entity to indicate that this Bean is EntityBean. Every persistent POJO class is an Entity bean, which can be declared by using the @ Entity annotation in the class definition. B. @ Table (name = "TableName") indicates the name of the database Table corresponding to the object Bean. @ Table is a Class-level annotation. Through the @ Table annotation, you can specify the names of tables, directories, and schemas for object bean ing. if no @ Table is defined, the system automatically uses the default value: short class name of the object (excluding the package name ). @ Table elements include a schema and a catalog attribute. You can specify the value if necessary. you can use the @ UniqueConstraint annotation to define the unique constraint (unique constraint) B. before the getXxx () method declaration, there are:. @ 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 it is allowed to be updated. 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.

 

C. @ GeneratedValue annotation defines how the ID field is generated. D. @ Version ing Version number attribute e. @ Column specifies the information of the Column 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 property does not need to be mapped to I. complex attributes: Association, inheritance, component, federated primary key, set C. link/object ing. one-to-many relationship: @ onetoworkflow indicates that the link is a one-to-many relationship. The following are the attributes of @ onetoworkflow annotation: 1> attributes of the targetEntity Class type. 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 set from: CascadeType. PERSIST (cascade new); CascadeType. REMOVE (cascade delete); CascadeType. REFRESH (cascade REFRESH); CascadeType. select one or more in MERGE (cascade update. Another option is CascadeType. ALL, which indicates that ALL four items are selected. 4> fatch FetchType. 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 primary class (in this example, the Order class) is loaded. The latter indicates that the relational 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 connection relationship. The optional = false join relationship is inner join, and the optional = true join relationship 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: @ OneToOne annotation, which 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 the 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 at 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.