Sword refers to architect series-hibernate need to master the annotation

Source: Internet
Author: User

1, one-to-many relationship configuration
@Entity @table (name = "T_order") public class Order {@Id @generatedvalue private int id;private String name;     /* * This property defines a cascade relationship between classes and 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: Order and OrderItem have a cascade relationship, then when you delete an order, the OrderItem object to which it should be deleted is also removed     . If the OrderItem also has a cascade relationship with other objects, then the operation will continue to execute recursively.     *      * cascadetype.persist (Cascade New)  appears to be only possible after the associated object is saved separately     * cascadetype.remove (cascade Delete) has cascading effects     * Cascadetype.refresh (cascade refresh)     * Cascadetype.merge (cascading update)     * Cascadetype.all (Select all four)     *      * cascading means allowing you to perform a cascade operation, such as cascading deletes, when cascading new is not allowed     *      * * The Mappedby property value is a variable name of a party defined in multiparty, and a bidirectional relationship needs to be defined     /@OneToMany ( Cascade ={Cascadetype.all},   fetch = Fetchtype.eager,        mappedby = "Order",             targetentity = Orderitem.class  ) Private set<orderitem> OrderItems = new hashset<orderitem> ();//Omit}

Declare a class as an entity by @entity annotations bean//through @Table annotations You can specify a table for entity bean mappings, the Name property represents the names of the tables that the entity corresponds to, and if there is no//definition @Table, Then the system automatically uses the default value: The class name of the entity (without the package name) @Entity @table (name = "T_orderitem") public class OrderItem implements Java.io.Serializable { Private static final Long Serialversionuid = 1l;//The primary key for the tag attribute//@Id//Represents the field in the table where the persisted property is mapped, and if the property name is the same as the field name in the table, you can omit the @column annotation ,//There are two other ways to mark, one is placed before the property, the other is placed before the Getter method//@Column (name = "employee_id")//* Table generator. The value of the current primary key is saved separately in a database table, and the value of the primary key is obtained each time from the specified table, and the way in which the primary key is generated is very common. This method of generating a primary key can be applied to any database, without worrying about the problem caused by the incompatibility of the different number of data bases.     It is recommended to manage the primary key in this way, it is convenient to centrally manage the primary key of the table, and replacing the data * Library will not cause great problems.         *//* @TableGenerator (name= "Tab-store",//the name of the table primary key generation policy, which can be customized, is referenced in the "generator" value set in @generatedvalue Table= "generator_table",//table generation policy persisted table name, is the table that manages the other table primary key pkcolumnname = "G_key",///Table Generator column name, used to hold the other table's primary key key name, this column name is with the table The fields in the pkcolumnvalue= "EMPLOYEE_PK",///entity table corresponding to the primary key name in the generator table, you can customize the column name in//table builder, the next value of the Entity table primary key, assuming that the employ in the EMPLOYEE table        EE_ID the maximum is 2, then the key name value for the primary key of the entity table in the generator table is 3 Valuecolumnname = "G_value", allocationsize=1//indicates the increment of the primary key value each time, for example, set to 1, that is, each time a new record is created automatically add 1, the default is 50) */     /* * Define the primary key generation policy, where tablegenerator is used, so the primary key generation strategy is generationtype.table, * The name of the generated primary key policy is the "Tab-store" defined earlier.  * * strategy = Generationtype.auto or strategy = generationtype.sequence, SEQUENCE sequence is used because identity autogrow is not supported in Oracle data *     To use it, you have to create a sequence in the database.     * * When using SQL Server as a database, if you want to use auto or identity generation policy, be sure to add an identity identity to the primary key, such as identity. * However, for auto, it is the most suitable self-increment primary key generation strategy based on different databases.     If you use MySQL, the primary key defines auto_increment.     * If it is Oracle, create a sequence to implement the self-increment. * * * */@Id//@Column (name = "Id")//@TableGenerator (name = "Tab-store", table = "Generator_table", Pkcolumnname = "G _key ", Pkcolumnvalue =" ORDERITEM_PK ", Valuecolumnname =" G_value ", allocationsize = 1)//@GeneratedValue (strategy = Gener ationtype.table, generator = "Tab-store") @GeneratedValueprivate Integer ID; private String name; /* The optional property is defined if the associated class must exist and the value is false when both sides of the association class must exist, and if the relationship is not present on the maintenance side, the result of the queryIs null. When the value is true, the relationship is maintained and the result of the query is still returned to the maintenance side of the relationship, and the property that points to the maintenance side of the relationship on the relationship maintenance side is null.   The default value of the optional property is true. The optional property actually specifies a join query relationship between the associated class and the associated class, such as Optional=false when the join query relationship is a inner join, optional=true when the join query relationship is a LEFT join. */@ManyToOne (cascade ={cascadetype.all},optional = False, Fetch=fetchtype.lazy, Targetentity=order.class) @JoinColum          N (name = "order_id")//in relation to the maintenance side need to establish a foreign key column to point to the primary key column of the relationship maintenance side private order order; Manytoone represents multiple employee correspondence with a department,dept_id field added to the Employee table//omitted}

  

2, many-to-many relationship configuration

@Entity @table (name = "Teacher") public class Teacher implements java.io.Serializable {private static final long serialvers Ionuid = 1L; @Id @generatedvalueprivate Integer Id @Column (name = "Name", length = 100)//column for table in database, maximum length is 100private String name;//@ManyToMany Note that teacher is one end of a many-to-many relationship. /* * @JoinTable describes the data table relationships for many-to-many relationships. * The name attribute specifies the intermediate table name, Joincolumns defines the foreign key relationship between the intermediate table and the teacher table. * The Inversejoincolumns attribute defines the foreign key relationship between the intermediate table and the other end (Student). *    /@JoinTable (    name= "Teacher_student",    joincolumns = {@JoinColumn (name= "teacher_id")},    inversejoincolumns={@JoinColumn (name= "student_id")}    ) @ManyToMany (cascade = cascadetype.all, fetch = Fetchtype.lazy) Private set<student> students = new hashset<student> ();        Omitted

  

@Entity @table (name = "Student") public class Student implements Serializable {private static final long Serialversionuid = 1L; @Id @generatedvalueprivate integer Id; @Column (name = "name") private String name; @Column (name = "Age") Private Integer age;//@ManyToMany annotation Indicates that student is one side of a many-to-many relationship, the Mappedby attribute defines the maintenance side of student as a bidirectional relationship//has and only one entity specifies the Mappedby attribute// This teachers property generates the corresponding TEACHERS_ID field in the database @manytomany (cascade = cascadetype.all, Mappedby = "Students") private set< teacher> teachers = new hashset<teacher> ();//omitted}

  

3. Use of the inheritance relationship in Hibernate

Hibernate's inheritance map contains three different strategies:

    1. Use one table per cluster class
    2. One table per subclass
    3. Each specific within a table (with restrictions)

JPA also supports 3 types of inherited forms:


1.Single table strategy, a single table policy, a table containing all the data of the base class and subclasses, in many cases using such a redundant design, through a discriminator to distinguish
2.Table per class strategy, each sub-class corresponds to a table, each table has properties of the base class
3.Join strategy, is still a table for each subclass, but this table does not contain the properties of the base class, only the extended properties of this subclass, the properties of the shared base class

(1) Single-table strategy

Using a single-table strategy, @discriminatorcolumn determines the field and type//@DiscriminatorValue annotation of the flag value, and when the animal type of entity is stored in the database, JPA will automatically assign the value of animal to the Animaltype field @entity@inheritance (strategy=inheritancetype.single_table) @DiscriminatorColumn ( Name= "Animaltype") @DiscriminatorValue ("Animal") public class Animal {private int id;private String name;@ id@generatedvaluepublic int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} @Entity @discriminatorvalue ("Cat") public class Cat extends Animal {private String catname;        Omit} @Entity @discriminatorvalue (value= "Dog") public class Dog extends Animal{private String dogname;//Omit}

 

(2) Table per Class

With the table per class policy, each subclass will have its own tables, and all of the properties in the base class are independently owned and not shared with each other.

 

@Entity @inheritance (strategy=inheritancetype.table_per_class) public CLASS Animal {private int id;private String name; @Id @generatedvalue (strategy=generationtype.table) public int getId () {return Id;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} @Entity @inheritance (strategy=inheritancetype.table_per_class) public CLASS Cat extends Animal {private String catname; Public String Getcatname () {return catname;} public void Setcatname (String catname) {this.catname = CatName;}} @Entity @inheritance (strategy=inheritancetype.table_per_class) public CLASS Dog extends Animal{private String dogname; Public String Getdogname () {return dogname;} public void Setdogname (String dogname) {this.dogname = Dogname;}}

  

(3) Join strategy

Each subclass also builds tables independently, and the base class builds tables independently, except that all the subclasses of the table have extended attributes, and they share the base class table

@Entity @inheritance (strategy=inheritancetype.joined) public class Animal {private int id;private String name;@ id@generatedvaluepublic int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} @Entity @primarykeyjoincolumn (name= "CatId") public class Cat extends Animal {private string Catname;public string Getcatname () {return catname;} public void Setcatname (String catname) {this.catname = CatName;}} @Entity @primarykeyjoincolumn (name= "Dogid") public class Dog extends Animal{private string Dogname;public string Getdogname () {return dogname;} public void Setdogname (String dogname) {this.dogname = Dogname;}}

  

Reference article:

1, http://www.360doc.com/content/11/0906/22/1542811_146326974.shtml

Sword refers to architect series-hibernate need to master annotation

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.