Hibernate(三)

注解高级(原文再续书接上一回)

5.双向关联

A.一对一

 1 package com.rong.entity;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.FetchType;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.GenerationType;
 7 import javax.persistence.Id;
 8 import javax.persistence.OneToOne;
 9 import javax.persistence.Table;
10 
11 @Entity
12 @Table(name="t_citizen")
13 public class Citizen {
14     @Id
15     @GeneratedValue(strategy=GenerationType.AUTO)
16     private int id;
17     private String name;
18     private int sex; 
19     @OneToOne(targetEntity=IDcard.class,fetch=FetchType.LAZY,mappedBy="citizen") // 不维护关联关系(主表)
20     private IDcard iDcard;                                    //由iDcard对象的成员变量citizen来维护
21     public int getId() {
22         return id;
23     }
24     public void setId(int id) {
25         this.id = id;
26     }
27     public String getName() {
28         return name;
29     }
30     public void setName(String name) {
31         this.name = name;
32     }
33     public int getSex() {
34         return sex;
35     }
36     public void setSex(int sex) {
37         this.sex = sex;
38     }
39     public IDcard getiDcard() {
40         return iDcard;
41     }
42     public void setiDcard(IDcard iDcard) {
43         this.iDcard = iDcard;
44     }
45     @Override
46     public String toString() {
47         return "Citizen [id=" + id + ", name=" + name + ", sex=" + sex + ", iDcard=" + iDcard + "]";
48     }
49 }
 1 package com.rong.entity;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.FetchType;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.GenerationType;
 7 import javax.persistence.Id;
 8 import javax.persistence.JoinColumn;
 9 import javax.persistence.OneToOne;
10 import javax.persistence.Table;
11 
12 @Entity
13 @Table(name="t_idcard")
14 public class IDcard {
15     @Id
16     @GeneratedValue(strategy=GenerationType.AUTO)
17     private int cardid;
18     private String name;
19     private String addr;
20     @OneToOne(targetEntity=Citizen.class,fetch=FetchType.LAZY) // 维护关联关系(从表)
21     @JoinColumn(name="t_id",referencedColumnName="id",unique=true)//生成外键列,参考citizen的id
22     private Citizen citizen;
23     public int getCardid() {
24         return cardid;
25     }
26     public void setCardid(int cardid) {
27         this.cardid = cardid;
28     }
29     public String getName() {
30         return name;
31     }
32     public void setName(String name) {
33         this.name = name;
34     }
35     public String getAddr() {
36         return addr;
37     }
38     public void setAddr(String addr) {
39         this.addr = addr;
40     }
41     public Citizen getCitizen() {
42         return citizen;
43     }
44     public void setCitizen(Citizen citizen) {
45         this.citizen = citizen;
46     }
47     @Override
48     public String toString() {
49         return "IDcard [cardid=" + cardid + ", name=" + name + ", addr=" + addr + ", citizen=" + citizen + "]";
50     }
51 }
 1 package com.rong.test;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
 7 import org.hibernate.cfg.Configuration;
 8 import org.hibernate.service.ServiceRegistry;
 9 import org.junit.Test;
10 
11 import com.rong.entity.Citizen;
12 import com.rong.entity.IDcard;
13 
14 public class HibernateTest {
15     @Test
16     public void test1(){
17         Configuration configuration=new Configuration().configure();
18         ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
19         SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
20         Session session = sessionFactory.openSession();
21         Transaction transaction = session.beginTransaction();
22         
23         Citizen citizen=new Citizen();
24         citizen.setName("容杰龙");
25         citizen.setSex(0);
26         IDcard iDcard=new IDcard();
27         iDcard.setAddr("广东");
28         iDcard.setCitizen(citizen);
29         
30         session.save(citizen);
31         session.save(iDcard);
32         //查找
33         Citizen person = (Citizen) session.get(Citizen.class, 1);
34         System.out.println(person);
35         IDcard card = (IDcard) session.get(IDcard.class, 1);
36         System.out.println(card);
37         transaction.commit();
38         session.close();
39         sessionFactory.close();
40     }
41 }

 

B.一对多(多的那端维护)

 1 package com.rong.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import javax.persistence.CascadeType;
 7 import javax.persistence.Entity;
 8 import javax.persistence.FetchType;
 9 import javax.persistence.GeneratedValue;
10 import javax.persistence.GenerationType;
11 import javax.persistence.Id;
12 import javax.persistence.OneToMany;
13 import javax.persistence.Table;
14 
15 @Entity
16 @Table(name="t_teacher")
17 public class Teacher {
18     @Id
19     @GeneratedValue(strategy=GenerationType.AUTO)
20     private int tid;
21     private String tname;
22     //一的一端(主表)
23     @OneToMany(targetEntity=Student.class // 指定关联的持久化
24             ,fetch=FetchType.LAZY // 延迟加载
25             ,cascade={CascadeType.REMOVE} // 级联删除(级联到关联的持久化类)
26             ,orphanRemoval=true // 删除孤儿记录
27             ,mappedBy="tea"//关联关系(外键列由从表维护), 写关联的持久化中哪个属性引用了它自己
28             )
29     private Set<Student> stu=new HashSet<Student>();
30     public int getTid() {
31         return tid;
32     }
33     public void setTid(int tid) {
34         this.tid = tid;
35     }
36     public String getTname() {
37         return tname;
38     }
39     public void setTname(String tname) {
40         this.tname = tname;
41     }
42     public Set<Student> getStu() {
43         return stu;
44     }
45     public void setStu(Set<Student> stu) {
46         this.stu = stu;
47     }
48     @Override
49     public String toString() {
50         return "Teacher [tid=" + tid + ", tname=" + tname + ", stu=" + stu + "]";
51     }
52 }
 1 package com.rong.entity;
 2 
 3 import javax.persistence.CascadeType;
 4 import javax.persistence.Entity;
 5 import javax.persistence.FetchType;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.GenerationType;
 8 import javax.persistence.Id;
 9 import javax.persistence.JoinColumn;
10 import javax.persistence.ManyToOne;
11 import javax.persistence.Table;
12 
13 @Entity
14 @Table(name="t_student")
15 public class Student {
16     @Id
17     @GeneratedValue(strategy=GenerationType.AUTO)
18     private int sid;
19     private String sname;
20     //多的一端 (从表,有外键)
21     @ManyToOne(targetEntity=Teacher.class// 指定关联的持久化类
22                 ,fetch=FetchType.LAZY // 延迟加载
23                 ,cascade=CascadeType.REMOVE// 级联删除
24                 )
25     //生成外键列
26     @JoinColumn(name="t_id",referencedColumnName="tid")
27     private Teacher tea;
28     public int getSid() {
29         return sid;
30     }
31     public void setSid(int sid) {
32         this.sid = sid;
33     }
34     public String getSname() {
35         return sname;
36     }
37     public void setSname(String sname) {
38         this.sname = sname;
39     }
40     public Teacher getTea() {
41         return tea;
42     }
43     public void setTea(Teacher tea) {
44         this.tea = tea;
45     }
46     @Override
47     public String toString() {
48         return "Student [sid=" + sid + ", sname=" + sname + ", tea=" + tea + "]";
49     }
50 }

 1 package com.rong.test;
 2 
 3 import java.util.Set;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.hibernate.Transaction;
 8 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
 9 import org.hibernate.cfg.Configuration;
10 import org.hibernate.service.ServiceRegistry;
11 import org.junit.Test;
12 
13 import com.rong.entity.Student;
14 import com.rong.entity.Teacher;
15 
16 public class HibernateTest {
17     @Test
18     public void test1(){
19         Configuration configuration=new Configuration().configure();
20         ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
21         SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
22         Session session = sessionFactory.openSession();
23         Transaction transaction = session.beginTransaction();
24 /*        //t_teacher 这个表是主表
25         Teacher teacher=new Teacher();
26         teacher.setTname("局长");
27         //t_student 是从表(有外键的是从表,需要维护关联关系)
28         Student student1=new Student();
29         student1.setSname("容杰龙");
30         student1.setTea(teacher);
31         Student student2=new Student();
32         student2.setSname("古月哥欠");
33         student2.setTea(teacher);
34         //保存的时候,必须先保存主表,后保存从表
35         session.save(teacher);
36         session.save(student1);
37         session.save(student2);*/
38         //查找
39         Teacher tea=(Teacher) session.get(Teacher.class, 1);
40         System.out.println(tea.getTname());
41         Set<Student> set = tea.getStu();
42         for (Student student : set) {
43             System.out.println(student.getSid()+":"+student.getSname());
44         }
45         
46         transaction.commit();
47         session.close();
48         sessionFactory.close();
49     }
50 }

C.多对多

 1 package com.rong.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import javax.persistence.Entity;
 7 import javax.persistence.FetchType;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.GenerationType;
10 import javax.persistence.Id;
11 import javax.persistence.ManyToMany;
12 import javax.persistence.Table;
13 
14 @Entity
15 @Table(name="t_teacher")
16 public class Teacher {
17     @Id
18     @GeneratedValue(strategy=GenerationType.AUTO)
19     private int tid;
20     private String tname;
21     //多的一端
22     @ManyToMany(targetEntity=Student.class
23                 ,fetch=FetchType.LAZY
24                 ,mappedBy="tea"// 老师这边不维护关联关系 (不用生成中间表)
25                 )
26     private Set<Student> stu=new HashSet<Student>();
27     public int getTid() {
28         return tid;
29     }
30     public void setTid(int tid) {
31         this.tid = tid;
32     }
33     public String getTname() {
34         return tname;
35     }
36     public void setTname(String tname) {
37         this.tname = tname;
38     }
39     public Set<Student> getStu() {
40         return stu;
41     }
42     public void setStu(Set<Student> stu) {
43         this.stu = stu;
44     }
45     @Override
46     public String toString() {
47         return "Teacher [tid=" + tid + ", tname=" + tname + ", stu=" + stu + "]";
48     }
49 }
 1 package com.rong.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import javax.persistence.Entity;
 7 import javax.persistence.FetchType;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.GenerationType;
10 import javax.persistence.Id;
11 import javax.persistence.JoinColumn;
12 import javax.persistence.JoinTable;
13 import javax.persistence.ManyToMany;
14 import javax.persistence.Table;
15 
16 @Entity
17 @Table(name="t_student")
18 public class Student {
19     @Id
20     @GeneratedValue(strategy=GenerationType.AUTO)
21     private int sid;
22     private String sname;
23     //多的一端
24     @ManyToMany(targetEntity=Teacher.class,fetch=FetchType.LAZY)
25     //生成中间表
26     @JoinTable(name="tea_stu" // 中间表的表名
27                 // @ManyToMany注解中没有加mappedBy表的主键列
28                 ,joinColumns={@JoinColumn(name="sid",referencedColumnName="sid")}
29                 // @ManyToMany注解中加了mappedBy属性的表的主键列
30                 ,inverseJoinColumns={@JoinColumn(name="tid",referencedColumnName="tid")})
31     private Set<Teacher> tea=new HashSet<Teacher>();
32     public int getSid() {
33         return sid;
34     }
35     public void setSid(int sid) {
36         this.sid = sid;
37     }
38     public String getSname() {
39         return sname;
40     }
41     public void setSname(String sname) {
42         this.sname = sname;
43     }
44     public Set<Teacher> getTea() {
45         return tea;
46     }
47     public void setTea(Set<Teacher> tea) {
48         this.tea = tea;
49     }
50     @Override
51     public String toString() {
52         return "Student [sid=" + sid + ", sname=" + sname + ", tea=" + tea + "]";
53     }
54 }
 1 package com.rong.test;
 2 
 3 import java.util.Set;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.hibernate.Transaction;
 8 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
 9 import org.hibernate.cfg.Configuration;
10 import org.hibernate.service.ServiceRegistry;
11 import org.junit.Test;
12 
13 import com.rong.entity.Student;
14 import com.rong.entity.Teacher;
15 
16 public class HibernateTest {
17     @Test
18     public void test1(){
19         Configuration configuration=new Configuration().configure();
20         ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
21         SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
22         Session session = sessionFactory.openSession();
23         Transaction transaction = session.beginTransaction();
24 /*        //t_teacher 这个表是主表
25         Teacher teacher1=new Teacher();
26         teacher1.setTname("陈局长");
27         Teacher teacher2=new Teacher();
28         teacher2.setTname("容部长");
29         //t_student 是从表(有外键的是从表,需要维护关联关系)
30         Student student1=new Student();
31         student1.setSname("容杰龙");
32         student1.getTea().add(teacher1);
33         student1.getTea().add(teacher2);
34         Student student2=new Student();
35         student2.setSname("古月哥欠");
36         student2.getTea().add(teacher1);
37         student2.getTea().add(teacher2);
38         //保存的时候,必须先保存主表,后保存从表
39         session.save(teacher1);
40         session.save(teacher2);
41         session.save(student1);
42         session.save(student2);
43 */        
44         //查找
45         Teacher tea=(Teacher) session.get(Teacher.class, 1);
46         System.out.println(tea.getTname());
47         Set<Student> set = tea.getStu();
48         for (Student student : set) {
49             System.out.println(student.getSid()+":"+student.getSname());
50         }
51         Student student=(Student) session.get(Student.class, 1);
52         System.out.println(student.getSname());
53         Set<Teacher> set2 = student.getTea();
54         for (Teacher teacher : set2) {
55             System.out.println(teacher.getTid()+":"+teacher.getTname());
56         }
57         transaction.commit();
58         session.close();
59         sessionFactory.close();
60     }
61 }

 

posted @ 2018-01-09 19:08  57容杰龙  阅读(138)  评论(0编辑  收藏  举报