Hibernate学习之路(四)
2021-06-21 09:05
标签:单向多对一 com nat conf 数据 _id 技术 import enc
简诉 单向多对一、单向一对多、双向一对多关系映射
一:单向多对一
1、学生表student和年级表Grade
2、类Student和类Grade
public class Student { private int id; private String name; private int age; private Grade grade; set/get.... }
public class Grade { private int id; private String name; set/get.... }
3、配置hbm.xml文件
Student.hbm.xml
span>mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">class name="Student"> class="native"> class="Grage" column="grade_id" foreign-key="fk_grade" not-null="true"> class>
Grade.hbm.xml
span>mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">class name="Grade"> class="native"> class>
4、测试
1 package cn.test; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 7 import cn.pojo.Grade; 8 import cn.pojo.Student; 9 import cn.pojo.User; 10 11 public class TestHibernate { 12 public static void main(String[] args) { 13 //通过Configuration对象创建SessionFactory对象 14 SessionFactory sf = new Configuration().configure().buildSessionFactory(); 15 //创建Session对象 16 Session s = sf.openSession(); 17 //开启事务 18 s.beginTransaction(); 19 20 //我们只需要关注这里的事务。 21 Grade grade = new Grade(); 22 grade.setName("进阶"); 23 s.save(grade); 24 Student s1 = new Student(); 25 s1.setName("李小龙"); 26 s1.setAge(22); 27 s1.setGrade(grade); 28 s.save(s1); 29 //提交事务 30 s.getTransaction().commit(); 31 //关闭Session 32 s.close(); 33 //关闭SessionFactory 34 sf.close(); 35 } 36 }
二:单向一对多
1、Grade类
1 public class Grade{ 2 private int id; 3 private String name; 4 private Setstudents = new HashSet (); 5 6 set/get.... 7 }
2、Grade.hbm.xml配置文件
package="cn.pojo"> class name="Grade"> class="native"> class> null="true"> class="Student"/>
三:双向一对多映射,就是两个hbm.xml都进行映射配置
Hibernate学习之路(四)
标签:单向多对一 com nat conf 数据 _id 技术 import enc
原文地址:http://www.cnblogs.com/DogLiLoveCat/p/7182420.html
上一篇:Unable to start process "dotnet-projectmodel-server" while starting VS2015 问题
下一篇:JSP-JSP内置对象