package dao.po; import java.util.Set; /** * 部门类 * * @author zl * */ public class Department { private int id; //部门的ID private String name; //部门的名称 private Set<Employee> emps; //部门下的所有员工 (一对多关系) }
package dao.po; /** * @author zl 员工类 */ public class Employee { private int id; // 员工的ID private String name; // 员工的名称 private Department depart; //员工所在部门 (是多对一关系) }
映射文件 :
<?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="dao.po"> <class name="Department"> <id name="id"> <generator class="native"/> </id> <property name="name" not-null="true" length="255" column="`name`"/> <set name="emps"> <!-- emps 是Department的一个属性 --> <key column="depart_id"></key> <!-- 通过员工表的 depart_id字段来关联,它是字段名 --> <one-to-many class="Employee"/> <!-- emps的类型是Employee --> </set> </class> </hibernate-mapping>
下面是重点:
<set name="emps"> <!-- emps 是Department的一个属性 -->
<key column="depart_id"></key> <!-- 通过员工表的 depart_id字段来关联,它是字段名 -->
<one-to-many class="Employee"/> <!-- emps的类型是Employee -->
</set>
<?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="dao.po"> <class name="Employee"> <id name="id"> <generator class="native"/> </id> <property name="name" not-null="true" length="255" column="`name`"/> <!-- 这里做多对一映射 --> <!-- name="depart"是Employee类的属性名 --> <!-- column="depart_id" 是表中字段名 --> <!-- --> <many-to-one name="depart" column="depart_id" not-null="true"></many-to-one> </class> </hibernate-mapping>
一对多 (一个部门 对 多个员工)
查询部门(部门下有员工)
public static void main(final String[] args) { final Department de = query(2); final Set<Employee> set = de.getEmps(); //本部门的所有员工 for (final Employee em : set) { System.out.println(em.getName()); } } /** * 查询部门(部门下有员工) * * @param id * 部门ID * @return 部门对象 */ public static Department query(final int id) { Session session = null; try { session = HibernateUtil.getSeesion(); final Transaction tx = session.beginTransaction(); final Department de = (Department) session.get(Department.class, id); //按ID查 //因为 部门的 "员工" 属性会懒加载, //在session关闭后,调用de.getEmps()无法取到员工信息 //所以这里用 Hibernate.initialize(de.getEmps()) 提前加载一下. Hibernate.initialize(de.getEmps()); tx.commit(); return de; } finally { if (session != null) { session.close(); } } }