Hibernate中多对多

Posted 呦,你是个老母猪呦!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate中多对多相关的知识,希望对你有一定的参考价值。

 

学生 - 老师

 1 package com.zhangpn.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 public class Student {
 7     private Long id;
 8     private String name;
 9     private Set<Teacher> teachers = new HashSet<>();
10 
11     public Long getId() {
12         return id;
13     }
14 
15     public void setId(Long id) {
16         this.id = id;
17     }
18 
19     public String getName() {
20         return name;
21     }
22 
23     public void setName(String name) {
24         this.name = name;
25     }
26 
27     public Set<Teacher> getTeachers() {
28         return teachers;
29     }
30 
31     public void setTeachers(Set<Teacher> teachers) {
32         this.teachers = teachers;
33     }
34 
35     public Student() {
36     }
37 
38     public Student(String name, Set<Teacher> teachers) {
39         this.name = name;
40         this.teachers = teachers;
41     }
42 
43 }
Student
 1 package com.zhangpn.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 public class Teacher {
 7     private Long id;
 8     private String name;
 9     private Set<Student> students = new HashSet<>();
10 
11     public Long getId() {
12         return id;
13     }
14 
15     public void setId(Long id) {
16         this.id = id;
17     }
18 
19     public String getName() {
20         return name;
21     }
22 
23     public void setName(String name) {
24         this.name = name;
25     }
26 
27     public Set<Student> getStudents() {
28         return students;
29     }
30 
31     public void setStudents(Set<Student> students) {
32         this.students = students;
33     }
34 
35     public Teacher() {
36     }
37 
38     public Teacher(String name, Set<Student> students) {
39         this.name = name;
40         this.students = students;
41     }
42 
43 }
Teacher

学生配置 - 老师配置

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <hibernate-mapping>
 5     <class name="com.zhangpn.entity.Student" table="STUDENT">
 6         <id name="id" type="java.lang.Long">
 7             <column name="ID" />
 8             <generator class="native" />
 9         </id>
10         <property name="name" type="java.lang.String">
11             <column name="NAME" />
12         </property>
13         <set name="teachers" table="STUDENT_TEACHER" inverse="false" lazy="true">
14             <key>
15                 <column name="STUDENTID" />
16             </key>
17             <many-to-many class="com.zhangpn.entity.Teacher" column="TEACHERID"></many-to-many>
18         </set>
19     </class>
20 </hibernate-mapping>
Student.hbm.xml
 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <hibernate-mapping>
 5     <class name="com.zhangpn.entity.Teacher" table="TEACHER">
 6         <id name="id" type="java.lang.Long">
 7             <column name="ID" />
 8             <generator class="native" />
 9         </id>
10         <property name="name" type="java.lang.String">
11             <column name="NAME" />
12         </property>
13         <set name="students" table="STUDENT_TEACHER" inverse="false" lazy="true">
14             <key>
15                 <column name="TEACHERID" />
16             </key>
17             <many-to-many class="com.zhangpn.entity.Student" column="STUDENTID"></many-to-many>
18         </set>
19     </class>
20 </hibernate-mapping>
Teacher.hbm.xml

中间表

学生
id name
   
中间表
stu_id tea_id
   
老师
id name
   

 

 

 


 学生表

主键:ID


教师表

主键:ID


 

中间表: 

主键:STUDENTID、TEACHERID

外键:STUDENTID、TEACHERID


 

插入数据:

 1 package com.zhangpn.test;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.hibernate.boot.MetadataSources;
 9 import org.hibernate.boot.registry.StandardServiceRegistry;
10 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11 
12 import com.zhangpn.entity.Student;
13 import com.zhangpn.entity.Teacher;
14 
15 public class Test {
16 
17     public static void main(String[] args) {
18         SessionFactory sessionFactory = null;
19         final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
20         try {
21             sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
22             System.out.println("sessionFactory Normal Running...");
23         } catch (Exception e) {
24             System.out.println("Problem : sessionFactory!!!");
25             StandardServiceRegistryBuilder.destroy(registry);
26         }
27         Session session = sessionFactory.openSession();
28         session.beginTransaction();
29         // ------------------------------------------------------
30         Student student1 = new Student();
31         Student student2 = new Student();
32         Student student3 = new Student();
33         Student student4 = new Student();
34         student1.setName("张同学");
35         student2.setName("王同学");
36         student3.setName("李同学");
37         student4.setName("楚同学");
38         
39         Set<Student> students1 = new HashSet<>();
40         students1.add(student1);
41         students1.add(student2);
42         Set<Student> students2 = new HashSet<>();
43         students2.add(student3);
44         students2.add(student4);
45         Set<Student> students3 = new HashSet<>();
46         students3.add(student1);
47         students3.add(student2);
48         students3.add(student4);
49         
50         Teacher teacher1 = new Teacher("刘老师",students1);
51         Teacher teacher2 = new Teacher("姜老师",students2);
52         Teacher teacher3 = new Teacher("赵老师",students3);
53         
54         session.save(student1);
55         session.save(student2);
56         session.save(student3);
57         session.save(student4);
58         
59         session.save(teacher1);
60         session.save(teacher2);
61         session.save(teacher3);
62         
63         // ------------------------------------------------------
64         session.getTransaction().commit();
65         session.close();
66         sessionFactory.close();
67     }
68 
69 }
Java源码

控制台输出结果:

  1 六月 12, 2018 1:30:12 下午 org.hibernate.Version logVersion
  2 INFO: HHH000412: Hibernate Core {5.0.1.Final}
  3 六月 12, 2018 1:30:12 下午 org.hibernate.cfg.Environment <clinit>
  4 INFO: HHH000206: hibernate.properties not found
  5 六月 12, 2018 1:30:12 下午 org.hibernate.cfg.Environment buildBytecodeProvider
  6 INFO: HHH000021: Bytecode provider name : javassist
  7 六月 12, 2018 1:30:12 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
  8 INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
  9 六月 12, 2018 1:30:12 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
 10 WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
 11 六月 12, 2018 1:30:13 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
 12 WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
 13 六月 12, 2018 1:30:13 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
 14 WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
 15 六月 12, 2018 1:30:13 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
 16 INFO: HHH000401: using driver [null] at URL [jdbc:mysql://localhost:3306/zhangpn?serverTimezone=GMT&useSSL=false]
 17 六月 12, 2018 1:30:13 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
 18 INFO: HHH000046: Connection properties: {user=root, password=****, driver_class =com.mysql.cj.jdbc.Driver}
 19 六月 12, 2018 1:30:13 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
 20 INFO: HHH000006: Autocommit mode: false
 21 六月 12, 2018 1:30:13 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
 22 INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
 23 六月 12, 2018 1:30:14 下午 org.hibernate.dialect.Dialect <init>
 24 INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
 25 六月 12, 2018 1:30:14 下午 org.hibernate.boot.model.source.internal.hbm.ModelBinder bindProperty
 26 WARN: HHH90000003: Use of DOM4J entity-mode is considered deprecated
 27 六月 12, 2018 1:30:14 下午 org.hibernate.boot.model.source.internal.hbm.ModelBinder bindProperty
 28 WARN: HHH90000003: Use of DOM4J entity-mode is considered deprecated
 29 六月 12, 2018 1:30:14 下午 org.hibernate.boot.model.source.internal.hbm.ModelBinder bindProperty
 30 WARN: HHH90000003: Use of DOM4J entity-mode is considered deprecated
 31 六月 12, 2018 1:30:14 下午 org.hibernate.boot.model.source.internal.hbm.ModelBinder bindProperty
 32 WARN: HHH90000003: Use of DOM4J entity-mode is considered deprecated
 33 六月 12, 2018 1:30:14 下午 org.hibernate.boot.model.source.internal.hbm.ModelBinder bindProperty
 34 WARN: HHH90000003: Use of DOM4J entity-mode is considered deprecated
 35 六月 12, 2018 1:30:14 下午 org.hibernate.boot.model.source.internal.hbm.ModelBinder bindProperty
 36 WARN: HHH90000003: Use of DOM4J entity-mode is considered deprecated
 37 六月 12, 2018 1:30:14 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
 38 INFO: HHH000228: Running hbm2ddl schema update
 39 sessionFactory Normal Running...
 40 Hibernate: 
 41     insert 
 42     into
 43         STUDENT
 44         (NAME) 
 45     values
 46         (?)
 47 Hibernate: 
 48     insert 
 49     into
 50         STUDENT
 51         (NAME) 
 52     values
 53         (?)
 54 Hibernate: 
 55     insert 
 56     into
 57         STUDENT
 58         (NAME) 
 59     values
 60         (?)
 61 Hibernate: 
 62     insert 
 63     into
 64         STUDENT
 65         (NAME) 
 66     values
 67         (?)
 68 Hibernate: 
 69     insert 
 70     into
 71         TEACHER
 72         (NAME) 
 73     values
 74         (?)
 75 Hibernate: 
 76     insert 
 77     into
 78         TEACHER
 79         (NAME) 
 80     values
 81         (?)
 82 Hibernate: 
 83     insert 
 84     into
 85         TEACHER
 86         (NAME) 
 87     values
 88         (?)
 89 Hibernate: 
 90     insert 
 91     into
 92         STUDENT_TEACHER
 93         (TEACHERID, STUDENTID) 
 94     values
 95         (?, ?)
 96 Hibernate: 
 97     insert 
 98     into
 99         STUDENT_TEACHER
100         (TEACHERID, STUDENTID) 
101     values
102         (?, ?)
103 Hibernate: 
104     insert 
105     into
106         STUDENT_TEACHER
107         (TEACHERID, STUDENTID) 
108     values
109         (?, ?)
110 Hibernate: 
111     insert 
112     into
113         STUDENT_TEACHER
114         (TEACHERID, STUDENTID) 
115     values
116         (?, ?)
117 Hibernate: 
118     insert 
119     into
120         STUDENT_TEACHER
121         (TEACHERID, STUDENTID) 
122     values
123         (?, ?)
124 Hibernate: 
125     insert 
126     into
127         STUDENT_TEACHER
128         (TEACHERID, STUDENTID) 
129     values
130         (?, ?)
131 Hibernate: 
132     insert 
133     into
134         STUDENT_TEACHER
135         (TEACHERID, STUDENTID) 
136     values
137         (?, ?)
138 六月 12, 2018 1:30:14 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
139 INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/zhangpn?serverTimezone=GMT&useSSL=false]
控制台输出信息

学生表


中间表


老师表


 

以上是关于Hibernate中多对多的主要内容,如果未能解决你的问题,请参考以下文章

hibernate的映射之三(多对多单向关联)

Laravel中多对多关系的多重搜索子句

Hibernate框架进阶(中篇)之多表关系

XAF中多对多关系 (XPO)

Java中多对多映射关系

数据库中多对多关系及其实现