hibernate映射之多对多双向
生活随笔
收集整理的這篇文章主要介紹了
hibernate映射之多对多双向
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
數(shù)據(jù)模型
?
teacher表
?
student表
?
t_tea_stu表
?
實體對象模型
Teacher private int tid;private String tname;private Set<Student> students; Student private int sid;private String sname;private Set<Teacher> teachers;xml配置信息:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.skyedu.bean"><class name="Teacher" table="teacher"><id name="tid" column="tid" ><generator class="native"></generator></id><property name="tname" column="tname" length="30"></property><set name="students" table="t_tea_stu" cascade="save-update"><key column="tid"></key><many-to-many class="Student" column="sid" ></many-to-many></set></class> </hibernate-mapping>?
?
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.skyedu.bean"><class name="Student" table="student"><id name="sid" column="sid" ><generator class="native"></generator></id><property name="sname" column="sname" length="32" ></property><set name="teachers" table="t_tea_stu" cascade="save-update"><key column="sid"></key><many-to-many class="Teacher" column="tid" ></many-to-many></set></class> </hibernate-mapping>?
測試代碼:
Session session = HibernateUtil.getSession();Transaction transaction = session.beginTransaction();try{Student student1 = new Student();student1.setSname("張三1");Student student2 = new Student();student2.setSname("張三2");Student student3 = new Student();student3.setSname("張三3");Student student4 = new Student();student4.setSname("張三4");Student student5 = new Student();student5.setSname("張三5");Teacher teacher1 = new Teacher();teacher1.setTname("王五1");Set<Student> students1 = new HashSet<Student>();students1.add(student1);students1.add(student2);students1.add(student3);teacher1.setStudents(students1);Teacher teacher2 = new Teacher();teacher2.setTname("王五2");Set<Student> students2 = new HashSet<Student>();students2.add(student1);students2.add(student4);students2.add(student5);teacher2.setStudents(students2);session.save(teacher1);session.save(teacher2);transaction.commit();}catch(Exception e){transaction.rollback();}finally{HibernateUtil.closeSession(session);}?
?
?
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/weidan/archive/2013/02/04/2892146.html
總結(jié)
以上是生活随笔為你收集整理的hibernate映射之多对多双向的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多线程java_初学Java要注意什么
- 下一篇: WordPress yolink Sea