先看两个映射关系:
部门:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hyy.hibernate.one_to_many.domain"> <class name="Department"> <id name="id">
<generator class="native"/>
</id> <property name="name"/> <property name="address"/> <set name="emps" cascade="save-update">
<key column="depart_id"/>
<one-to-many class="Employee"/>
</set> </class> </hibernate-mapping>
员工:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hyy.hibernate.one_to_many.domain"> <class name="Employee"> <id name="id">
<generator class="native"/>
</id> <property name="name"/> <property name="birthday"/> <!-- 多对一的映射,首先会找到depart引用的类,拿column(外键)与Department的id一起比较 -->
<many-to-one name="depart" column="depart_id" lazy="false" fetch="join"/> </class> </hibernate-mapping>
测试类:
//创建部门
Department department = new Department();
department.setName("dept");
department.setAddress("department"); //创建员工1
Employee employee1 = new Employee();
employee1.setName("11111"); //创建员工2
Employee employee2 = new Employee();
employee2.setName("22222"); //在此只添加一个部门和一个员工(我们下面再会添加一个)
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
department.getEmps().add(employee1);
session.save(department);
transaction.commit();
session.close(); System.out.println("以下为emp设置dept,用load,它不会产生查询!如果用get则有查询!用load是正确的");
Session session2 = HibernateUtil.getSession();
Transaction transaction2 = session2.beginTransaction(); //重点看这里
Department department1 =(Department) session2.load(Department.class,1);
employee2.setDepart(department1); session2.save(employee2);
transaction2.commit();
session2.close();
System.out.println("—————————————数据插入完成—————————————————");
总结:我们添加一个对象的时候,并且要添加的这个对象与另一方有关联,则我们可以把另一方的对象使用sesion.load方法将其代理出来,然后通过添加对象的set方法将关联对象设置进来。