2.2, hibernate with annotations to achieve a one-to-many, many-to-many relationship

Source: Internet
Author: User

A, one -to-many relationship

1, in the previous log with the. XML configuration file project, and then add a package to the Lib directory first-hibernate-jpa-2.0-api-1.0.0.final.jar

2. Create a new COM.ST.BEAN4 package and add two classes containing annotations to the package:

A), DeptBean2 class:

 1 package com.st.bean4; 2 3 Import Java.util.HashSet; 4 Import Java.util.Set; 5 6 7 Import Javax.persistence.Column; 8 Import javax.persistence.Entity; 9 Import javax.persistence.generatedvalue;10 Import javax.persistence.id;11 import javax.persistence.joincolumn;12 Import javax.persistence.onetomany;13 import javax.persistence.table;14 import Org.hibernate.annotations.Cascade;                                               Import org.hibernate.annotations.cascadetype;17 Import org.hibernate.annotations.genericgenerator;18 @Entity Specify the entity class @Table (name= "DEPT")//name of the corresponding table @Generic                                               Generator (name= "GenID", strategy= "increment")//declaring a primary key generation strategy in public class DeptBean2 {@Id                                Specify primary key @GeneratedValue (generator= "GenID")//Set Primary key generation strategy @Column (name= "ID")                              Specifies the correspondence between the attributes in the class and the columns in the table. Id;27 @Column (name= "name")Specifies the corresponding relationship between a property in a class and a column in a table. name;29 3//Specify a one-to-many relationship in the list 1 @Cascade (Value={cascadetype.save_update})//Set Cascade relationship @JoinColumn (name= "dept_id")/ /Specifies the foreign key of the appearance corresponding to the primary key of this class. set<employeebean2> emp = new hashset<employeebean2> (); @Override35 p  Ublic String toString () {Deptbean return "id=" + ID + ", name=" + name + "]"; PNs}38 public Long getId () {id;40}41 public void setId (long id) {$ this.id = id;43}44 public String get     Name () {name;46}47 public void SetName (String name) {this.name = name;49}50 Public set<employeebean2> getemp () {emp;52}53 public void Setemp (Set<employeebean2&gt ; EMP) {this.emp = emp;55}56}

b), Employeebean class:

 1 package com.st.bean4; 2 3 Import Javax.persistence.Column; 4 Import javax.persistence.Entity; 5 Import Javax.persistence.GeneratedValue; 6 Import Javax.persistence.Id; 7 Import Javax.persistence.JoinColumn; 8 Import Javax.persistence.ManyToOne; 9 Import javax.persistence.table;10 Import org.hibernate.annotations.genericgenerator;12 @Entity//Specify an entity @Tabl E (name= "employee")//Specify the name of the table @GenericGenerator (name= "GenID", strategy= "increment")//Declare primary key generation policy-public class                EmployeeBean2 {@Id//Specify PRIMARY key @GeneratedValue (generator= "GenID") Set the primary key generation strategy @Column (name= "ID")//the corresponding relationship between a property in a class and a column name in a table. id;2 1 @Column (name= "name") of the private string name;23 @Column (name= "SEX") of the private string sex;25 @Column (NA Me= "JOB")-Private String job;27 @ManyToOne//Specify many-to-one relationship//Specify many-to-one relationship @JoinColumn (name= "DEP t_id ") 29//An employee corresponds to a department number, so there is no need to assemble the private DeptBean2 dept;         Note that this place does not have a new object, otherwise it will not run to public long getId () {return id;33}34 public void setId (long id) {35  This.id = id;36}37 public String getName () {# return name;39}40 public void SetName (string Name) {this.name = name;42}43 public String getsex () {sex;45-return,}46-public voi     D setsex (String sex) {This.sex = sex;48}49 public String getjob () {return job;51}52 public void Setjob (String job) {this.job = job;54}55 public DeptBean2 getdept () {# D ept;57}58 public void setdept (DeptBean2 dept) {$ this.dept = dept;60}61 @Override62 public String toString () {Employeebean [id= "+ ID +", name= "+ name +", sex= "+ sex64 +", j    ob= "+ Job +", dept= "+ Dept65 +"] "; 66 }67} 

3. The mapping of the above two classes is introduced in the Hibernate.cfg.xml file

1          <mapping class= "com.st.bean5.UserBean2"/>2          <mapping class= "com.st.bean5.RoleBean2"/>

4, add the corresponding test method in Beantest:

1     @Test 2 public     void Bean4test1 () {3         session session = Hibernatetools.opensession (); 4         Transaction Tran = Session.begintransaction (); 5         //First add a new data in dept, then associate a new data in employee 6         //deptbean2 dept = new DeptBean2 () 7         ///Read the data in dept first, And then on the basis of the reading is associated with a new data in employee 8         DeptBean2 dept = (DeptBean2) session.get (deptbean2.class,1l);//1l represents the primary key 9         EmployeeBean2 emp = new EmployeeBean2 (),         //dept.setname ("technical Department"),         emp.setname ("Chen Zejun")         ; Emp.setsex ("male"),         emp.setjob ("STM32"),         dept.getemp (). Add (EMP),         session.save (dept);         Confirm the submission of things         tran.commit ();     

 

Two, many-to-many relations

1. Create a new COM.ST.BEAN4 package and add two classes containing annotations to the package

A), UserBean2:

 1 package com.st.bean5; 2 Import Java.util.HashSet; 3 Import Java.util.Set; 4 5 Import Javax.persistence.Column; 6 Import javax.persistence.Entity; 7 Import Javax.persistence.GeneratedValue; 8 Import Javax.persistence.Id; 9 Import javax.persistence.joincolumn;10 import javax.persistence.jointable;11 import Javax.persistence.ManyToMany; Import javax.persistence.table;13 Import org.hibernate.annotations.cascade;15 Import                                                ORG.HIBERNATE.ANNOTATIONS.CASCADETYPE;16 Import org.hibernate.annotations.genericgenerator;17 @Entity Entity @Table (name= "T_user")//Table name @GenericGenerator (name=                                                "GenID", strategy= "increment")//declaring primary key generation strategy, public class UserBean2 {@Id                                 Specify primary key @GeneratedValue (generator= "GenID")//Set Primary key generation strategy @Column (name= "ID") Specifies the corresponding relationship between the properties of the class and the fields of the table. Id;26 @Column (name= "name") The private string name;28 @Column (name= "SEX") in private string sex;30 @ManyToMany Specify a many-to-many relationship @Cascade (value={cascadetype.save_update})//Set a cascade relationship of @JoinTable (name= "User_ro LE ",//Specify the third table joincolumns={@JoinColumn (name=" user_id ")},//This table corresponds to the foreign key of the intermediate table inversejoincolumns={@JoinColumn (name= "role_id")})//the corresponding relationship between the other table and the foreign key of the third table. Private Set<rolebea n2> role = new hashset<rolebean2> (); n Public long GetId () {PNS return id;38}39 public void S Etid (Long id) {this.id = id;41}42 public String getName () {for name;44,}45 Publi     c void SetName (string name) {this.name = name;47}48 public String getsex () {return sex;50 }51 public void Setsex (String sex) {this.sex = sex;53}54 public set<rolebean2> getrole () {return to role;}57 public void Setrole (set<rolebean2> role) {this.role = role;59}60 @Override61 Public String toString () {UserBean [id=] + ID + ", name=" + name + ", sex=" + sex63 + " , role= "+ role +"] "; 64}65}

b), Rolebean class:

 1 package com.st.bean5; 2 Import Java.util.HashSet; 3 4 Import Java.util.Set; 5 6 Import Javax.persistence.Column; 7 Import javax.persistence.Entity; 8 Import Javax.persistence.GeneratedValue; 9 Import javax.persistence.id;10 Import javax.persistence.joincolumn;11 import javax.persistence.jointable;12 Import JAVAX.PERSISTENCE.MANYTOMANY;13 Import javax.persistence.table;14 Import org.hibernate.annotations.cascade;16                                              Import org.hibernate.annotations.cascadetype;17 Import org.hibernate.annotations.genericgenerator;18 @Entity Entity @Table (name= "t_role")//Table name @GenericGenerator (NA                                              Me= "GenID", strategy= "increment")//Declaration primary key generation policy, public class RoleBean2 {@Id                                 Primary key @GeneratedValue (generator= "GenID")//Set Primary key generation strategy @Column (name= "ID") The correspondence between the attributes in the class and the fields of the table. Id;27 @Column (name= "POST")/PRIvate String post;//position @Column (name= "pay")-private int pay;        Salary @ManyToMany//Many-to-many relationship @Cascade (value={cascadetype.save_update}) Cascade Relationship @JoinTable (name= "User_role",//Intermediate table name joincolumns={@JoinColumn (name= "role_id")},//The foreign key correspondence between this table and the intermediate table inversejoincolumns={@JoinColumn (name= "user_id")})//Another table corresponds to the foreign key of the intermediate table 3  6 private set<userbean2> user = new hashset<userbean2> (); PNs public Long getId ()         id;40}41 public void setId (long id) {$ this.id = id;43}44 public String getpost () {45 return post;46}47 public void Setpost (String post) {$ this.post = post;49}50 public int Getpay ( {pay;52}53 public void SetPay (int. pay) {si this.pay = pay;55}56 public SET&L T Userbean2> GetUser () {user;58 return}59 public void SetUser (set<userbean2> user) {This.user = user;61}62 @Override63 public String Tostrin G () {Rolebean [id=] + ID + ", post=" + post + ", pay=" + Pay + "]"; 65}66}

2, in Hibernate.cfg.xml introduced UserBean2 and RoleBean2 these two classes of mappings:

1          <mapping class= "com.st.bean5.UserBean2"/>2          <mapping class= "com.st.bean5.RoleBean2"/>

3. Add a test method to the Beantest class:

 1 @Test 2 public void Bean5test1 () {3//Get a session 4 sessions session = Hibernatetools.opensession (); 5//Open a thing 6 Transaction tran = Session.begintransaction (); 7 UserBean2 user = new UserBean2 (); 8//RoleBean2 role = (RoleBean2) session.get (rolebean2.class,1l);         9 RoleBean2 role = new RoleBean2 (), User.setname ("Wang Wen Shi"), User.setsex ("male"); 13 Role.setpost ("Doctor"), Role.setpay (10000), Role.getuser (). Add (user), SE         Ssion.save (role); 19//Confirm the submission of things tran.commit ();}22 @Test23 public void Bean5test2 () {24 Gets a session Sessions session = Hibernatetools.opensession (); +/* list<userbean> List = Session.crea         Tecriteria (userbean.class). List (); UserBean user:list) System.out.println (user); */29 String hql = "Select New Map (U.name as name,u.sex as sex,r.post as post,R.pay as pay) from UserBean2 u join u.role r "; list<map<string,object>> List = Session.createquery (h QL). List (); map<string,object> data:list) System.out.println (data); 33}

Third, note:

1. After introducing the jar package required for annotations, delete the Java EE 5 Library, or the class in the two jar package will conflict

2, in the multi-table operation is best to set the cascade relationship, otherwise the table operation to read a class of data, and then add a new class of data to this class to successfully operate on three tables.

2.2, hibernate with annotations to achieve a one-to-many, many-to-many relationship

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.