一、hbm.xml
1.TeacherEntityMTM.hbm.xml
1 <?xml version='1.0' encoding='utf-8'?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping package="com.sdkj.hibernate.domain"> 6 7 <class name="TeacherEntity_Many_To_Many" table="mtm_teacher" schema="678"> 8 <id name="tid" type="int"> 9 <column name="tid"></column> 10 <generator class="native"></generator> 11 </id> 12 <property name="tname" column="tname"/> 13 14 <set name="courseEntities" table="teacher_course"> 15 <key> 16 <column name="pid"/> 17 </key> 18 <many-to-many class="CourseEntity" column="cid"></many-to-many> 19 </set> 20 </class> 21 </hibernate-mapping>
2.CourseEntity.hbm.xml
1 <?xml version='1.0' encoding='utf-8'?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping package="com.sdkj.hibernate.domain"> 6 <class table="mtm_course" name="CourseEntity" schema="678"> 7 <id name="cid"> 8 <column name="cid"></column> 9 <generator class="native"></generator> 10 </id> 11 <property name="cname" column="cname"></property> 12 </class> 13 </hibernate-mapping>
二、TestDXManyToMany
1 package com.sdkj.hibernate.controller; 2 3 import com.sdkj.hibernate.domain.CourseEntity; 4 import com.sdkj.hibernate.domain.TeacherEntity_Many_To_Many; 5 import com.sdkj.hibernate.util.CommonUtil; 6 import org.hibernate.Session; 7 import org.hibernate.SessionFactory; 8 import org.hibernate.Transaction; 9 import org.junit.jupiter.api.Test; 10 11 import java.util.HashSet; 12 import java.util.Set; 13 14 /** 15 * @Author wangshuo 16 * @Date 2022/4/9, 9:54 17 * 单向多对多 -- 只有teacher查询course的场景 18 */ 19 public class TestDXManyToMany extends CommonUtil { 20 21 @Test 22 public void test(){ 23 24 SessionFactory sessionFactory = getSessionFactory(); 25 Session session = sessionFactory.openSession(); 26 Transaction transaction = session.beginTransaction(); 27 28 TeacherEntity_Many_To_Many teacherEntity_many_to_many = new TeacherEntity_Many_To_Many(); 29 teacherEntity_many_to_many.setTname("李老师"); 30 31 CourseEntity courseEntity = new CourseEntity(); 32 courseEntity.setCname("大学语文-必修"); 33 CourseEntity courseEntity1 = new CourseEntity(); 34 courseEntity1.setCname("经典唐诗宋词"); 35 36 Set<CourseEntity> set = new HashSet<>(); 37 set.add(courseEntity); 38 set.add(courseEntity1); 39 teacherEntity_many_to_many.setStudentEntities(set); 40 41 session.save(teacherEntity_many_to_many); 42 session.save(courseEntity); 43 session.save(courseEntity1); 44 45 commit(transaction,sessionFactory,session); 46 } 47 }
本文来自博客园,作者:荣慕平,转载请注明原文链接:https://www.cnblogs.com/rongmuping/articles/16121051.html