hibernate建表多对多建表

Student.java

 1 package cn.itcast.hiberate.sh.domain;
 2 
 3 import java.util.Set;
 4 
 5 public class Student {
 6     private Long sid;
 7     private String sname;
 8     private String description;
 9     Set<Course> courses;
10     
11     
12     public Set<Course> getCourses() {
13         return courses;
14     }
15     public void setCourses(Set<Course> courses) {
16         this.courses = courses;
17     }
18     public Long getSid() {
19         return sid;
20     }
21     public void setSid(Long sid) {
22         this.sid = sid;
23     }
24     public Student(String sname, String description) {
25         super();
26         this.sname = sname;
27         this.description = description;
28     }
29     public Student() {
30         // TODO Auto-generated constructor stub
31     }
32     public String getSname() {
33         return sname;
34     }
35     public void setSname(String sname) {
36         this.sname = sname;
37     }
38     public String getDescription() {
39         return description;
40     }
41     public void setDescription(String description) {
42         this.description = description;
43     }
44     
45 }

Student.hbm.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 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="cn.itcast.hiberate.sh.domain.Student">
 6         <id name="sid" length="5">
 7             <generator class="increment"></generator>
 8         </id>
 9         <property name="sname" length="20"></property>
10         <property name="description" length="100"></property>
11         <!-- 
12             table就是用来描述第三张表
13             key 用来描述外键,多对多的关系看对哪张表建立映射
14             此表是描述Student信息的,所以 key中 column写sid
15             
16             many-to-many 中用于建立关系的所以 在第三张表中关系用cid建立
17          -->
18         <set name="courses" table="student_course">
19             <key>
20                 <column name="sid"></column>
21             </key>
22             <many-to-many class="cn.itcast.hiberate.sh.domain.Course" column="cid">
23             </many-to-many >
24         </set>
25     </class>
26 </hibernate-mapping>

Course.java

 1 package cn.itcast.hiberate.sh.domain;
 2 
 3 import java.io.Serializable;
 4 import java.util.Set;
 5 
 6 public class Course implements Serializable {
 7     private Long cid;
 8     private String cname;
 9     private String description;
10     private Set<Student> students;
11     public Long getCid() {
12         return cid;
13     }
14     public void setCid(Long cid) {
15         this.cid = cid;
16     }
17     public String getCname() {
18         return cname;
19     }
20     public void setCname(String cname) {
21         this.cname = cname;
22     }
23     public String getDescription() {
24         return description;
25     }
26     public void setDescription(String description) {
27         this.description = description;
28     }
29     public Set<Student> getStudents() {
30         return students;
31     }
32     public void setStudents(Set<Student> students) {
33         this.students = students;
34     }
35     
36 }

Course.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 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="cn.itcast.hiberate.sh.domain.Course">
 6         <id name="cid" length="5" type="java.lang.Long">
 7             <generator class="increment"></generator>
 8         </id>
 9         <property name="cname" length="20" type="java.lang.String"></property>
10         
11         <property name="description" length="100" type="java.lang.String"></property>
12         <!-- 
13             set元素对应类中的set集合
14             通过set元素使classes表与student表建立关联
15                key是通过外键的形式让两张表建立关联,针对的是哪张表看哪个
16                one-to-many是通过类的形式让两个类建立关联
17             
18             cascade 级联
19                save-update
20                    1、当 保存班级的时候,对学生进行怎么样的操作
21                         如果学生对象在数据库中没有对应的值,这个时候会执行save操作
22                         如果学生对象在数据库中有对应的值,这个时候会执行update操作
23                delete
24                all
25             inverse  维护关系
26                true      不维护关系     
27                false     维护关系
28                default   false
29          -->
30         <set name="students" table="student_course">
31             <!-- 
32                 key是用来描述外键 哪张表就哪個外鍵
33                 <many-to-many> 中的cid 描述类与类之间的关系
34              -->
35             <key>
36                 <column name="cid"></column>
37             </key>
38             <many-to-many class="cn.itcast.hiberate.sh.domain.Student" column="sid">
39             </many-to-many>
40         </set>
41     </class>
42 </hibernate-mapping>

hibernate.cfg.xml

 1 <?xml version='1.0' encoding='utf-8'?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <!-- 
 7         一个session-factory只能连接一个数据库
 8     -->
 9 <session-factory>
10     <!-- 
11         数据库的用户名
12     -->
13     <property name="connection.username">root</property>
14     <!-- 
15         密码
16     -->
17     <property name="connection.password">friends</property>
18     <!-- 
19         url
20     -->
21     <property name="connection.url">
22         jdbc:mysql://localhost:3306/itcast_sh_hibernate_manyTomany
23     </property>
24     <!-- 
25         作用:根据持久化类和映射文件生成表
26         validate
27         create-drop
28         create
29         update
30     -->
31     <property name="hbm2ddl.auto">update</property>
32     <!-- 
33         显示hibernate内部生成的sql语句
34     -->
35     
36     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
37     <property name="show_sql">true</property>
38     <mapping resource="cn/itcast/hiberate/sh/domain/Course.hbm.xml" />
39     <mapping resource="cn/itcast/hiberate/sh/domain/Student.hbm.xml" />
40 
41 </session-factory>
42 </hibernate-configuration>

test.java

 1 package cn.itcast.hiberate.sh.test;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.cfg.Configuration;
 7 import org.junit.Test;
 8 
 9 import cn.itcast.hibernate.sh.utils.HiberanteUtils;
10 
11 public class CreateTable extends HiberanteUtils{
12 
13     @Test
14     public void createTable()
15     {
16         Configuration config=new Configuration();
17         config.configure();
18 //        SessionFactory sessionFactory=config.buildSessionFactory();
19 //        Session session=sessionFactory.openSession();
20 //        Transaction transaction=session.beginTransaction();
21 //        
22 //        
23 //        transaction.commit();
24 //        session.close();
25     }
26 }

 测试2

  1 package cn.itcast.hibernate.sh.test;
  2 
  3 import java.util.HashSet;
  4 import java.util.List;
  5 import java.util.Set;
  6 
  7 import org.hibernate.Session;
  8 import org.hibernate.Transaction;
  9 import org.junit.Test;
 10 
 11 import cn.itcast.hiberate.sh.domain.manytomany.Course;
 12 import cn.itcast.hiberate.sh.domain.manytomany.Student;
 13 import cn.itcast.hibernate.sh.utils.HiberanteUtils;
 14 
 15 /**
 16  * 1、新建一个课程
 17  * 2、新建一个学生
 18  * 3、新建课程的同时新建学生 级联
 19  * 4、已经存在一个课程,新建一个学生,建立课程和学生之间的关系
 20  * 5、已经存在一个学生,新建一个课程,建立课程和学生之间的关系
 21  * 6、已经存在一个课程,已经存在一个学生,建立关联
 22  * 7、把已经存在的一些学生加入到已经存在的一个课程中
 23  * 8、把一个学生加入到一些课程中
 24  * 9、把多个学生加入到多个课程中
 25  * 10、把一个已经存在的学生从一个已经的课程中移除
 26  * 11、把一些学生从一个已经存在的课程中移除
 27  * 12、把一个学生从一个课程转向到另外一个课程
 28  * 13、删除课程
 29  * 14、删除学生
 30  * @author Think
 31  *
 32  */
 33 public class ManyToManyTest extends HiberanteUtils{
 34     static{
 35         url = "cn/itcast/hiberate/sh/domain/manytomany/hibernate.cfg.xml";
 36     }
 37     @Test
 38     public void testCreateTable(){
 39         
 40     }
 41     
 42     @Test
 43     public void testSaveStudent_Cascade_Course_Save(){
 44         Session session = sessionFactory.openSession();
 45         Transaction transaction = session.beginTransaction();
 46         Student student = new Student();
 47         student.setSname("班长");
 48         student.setDescription("牛人");
 49         
 50         Course course = new Course();
 51         course.setCname("生理卫生");
 52         course.setDescription("很好");
 53         
 54         Set<Course> courses = new HashSet<Course>();
 55         courses.add(course);
 56         student.setCourses(courses);
 57         session.save(student);
 58         transaction.commit();
 59         session.close();
 60     }
 61     
 62     /**
 63      * 已经存在一个课程,新建一个学生,建立课程和学生之间的关系
 64      *    从课程角度出发
 65      */
 66     @Test
 67     public void testUpdateCourse_Cascade_Student_Save_R(){
 68         Session session = sessionFactory.openSession();
 69         Transaction transaction = session.beginTransaction();
 70         Course course = (Course)session.get(Course.class, 1L);
 71         Student student = new Student();
 72         student.setSname("班迷");
 73         student.setDescription("班丝:班长的钢丝");
 74         course.getStudents().add(student);
 75         session.save(student);
 76         transaction.commit();
 77         session.close();
 78     }
 79     
 80     /**
 81      * 已经存在一个课程,新建一个学生,建立课程和学生之间的关系
 82      *   从学生角度出发
 83      */
 84     @Test
 85     public void testSaveStudent_R(){
 86         Session session = sessionFactory.openSession();
 87         Transaction transaction = session.beginTransaction();
 88         Course course = (Course)session.get(Course.class, 1L);
 89         Student student = new Student();
 90         student.setSname("班迷");
 91         student.setDescription("班丝:班长的钢丝");
 92         Set<Course> courses = new HashSet<Course>();
 93         courses.add(course);
 94         student.setCourses(courses);
 95         session.save(student);
 96         transaction.commit();
 97         session.close();
 98     }
 99     
100     /**
101      * 已经存在一个课程,已经存在一个学生,建立关联
102      */
103     @Test
104     public void testR(){
105         Session session = sessionFactory.openSession();
106         Transaction transaction = session.beginTransaction();
107         Course course = (Course)session.get(Course.class, 1L);
108         Student student = (Student)session.get(Student.class, 2L);
109         student.getCourses().add(course);
110         transaction.commit();
111         session.close();
112     }
113     
114     /**
115      * 把学生3,4加入到课程1中
116      */
117     @Test
118     public void testR_Some(){
119         Session session = sessionFactory.openSession();
120         Transaction transaction = session.beginTransaction();
121         Course course = (Course)session.get(Course.class, 1L);
122         Student student = (Student)session.get(Student.class, 3L);
123         Student student2 = (Student)session.get(Student.class, 4L);
124         //注释的语句效率不如没有注释的语句,因为hibernate存在缓存,对于不同的对象student.getcourse()查询了两次sql语句
125         //而course.getStudent()则之执行一次查询语句
126 //        student.getCourses().add(course);
127 //        student2.getCourses().add(course);
128         course.getStudents().add(student2);
129         course.getStudents().add(student);
130         transaction.commit();
131         session.close();
132     }
133     
134     /**
135      * 把一个学生加入到一些课程中
136      */
137     @Test
138     public void testR_Some_2(){
139         Session session = sessionFactory.openSession();
140         Transaction transaction = session.beginTransaction();
141         Student student = (Student)session.get(Student.class, 3L);
142         List<Course> courseList = session.createQuery("from Course where cid in(1,2,3)").list();
143         student.getCourses().addAll(courseList);
144         transaction.commit();
145         session.close();
146     }
147     
148     /**
149      * 把学生从一个课程转移到另外一个课程
150      */
151     @Test
152     public void testTransform(){
153         Session session = sessionFactory.openSession();
154         Transaction transaction = session.beginTransaction();
155         Student student = (Student) session.get(Student.class, 3L);
156         Course course1 = (Course)session.get(Course.class, 1L);
157         Course course3 = (Course)session.get(Course.class, 3L);
158         student.getCourses().remove(course1);
159         student.getCourses().add(course3);
160         transaction.commit();
161         session.close();
162     }
163 }
原文地址:https://www.cnblogs.com/friends-wf/p/3776405.html