标签:单向多对一 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
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Student"> <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> <property name="age"></property> <!-- 多对一 name 表示属性名 class 指明 属性对应的类 column指 数据库表中的列名 --> <many-to-one name="grade" class="Grage" column="grade_id" foreign-key="fk_grade" not-null="true"></many-to-one> </class> </hibernate-mapping>
Grade.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Grade"> <id name="id"> <generator class="native"></generator> </id> <property name="name"></property> </class> </hibernate-mapping>
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 Set<Student> students = new HashSet<Student>(); 5 6 set/get.... 7 }
2、Grade.hbm.xml配置文件
<hibernate-mapping package="cn.pojo"> <class name="Grade"> <!-- 主键生成策略 --> <id name="id" column="id"> <generator class="native"></generator> </id> <!-- 实体类的属性 --> <property name="name"></property> <!-- set是 Grade中的集合属性 name属性名称 --> <set name="students"> <!-- key表示外键 column外键列名--> <key column="grade_id" not-null="true"></key> <!-- one-to-many 一对多 类Grade 中 students 所表示类型 --> <one-to-many class="Student"/> </set> </class> </hibernate-mapping>
三:双向一对多映射,就是两个hbm.xml都进行映射配置
标签:单向多对一 com nat conf 数据 _id 技术 import enc
原文地址:http://www.cnblogs.com/DogLiLoveCat/p/7182420.html