2.一对多关系映射:

上面提到的多个员工对应于一个部门,是多对一的关系,如果一个部门有多个员工,则用“一对多”的关系来表示这个关系,现接上例继续,以实现一对多的关系映射。具体操作步骤如下:

>>步骤一,在Department.java中增加如下内容:privateSet<Employee>emps;及相应的get/set方法。

>>步骤二,修改Department的实体配置文件。在class元素下增加如下内容:

<setname="emps">

<keycolumn="depart_id"></key>

<one-to-manyclass="Employee"/>

</set>

说明:<set>元素同样是指定一个属性,只不过是指定一个特殊的属性,key中的column为映射文件的外键,这里是指Employee.java相关的实体对象的外键。<one-to-manyclass="Employee"/>中的class表示关联的外键为Employee对象,也即Set中泛型机制指定的类。

>>步骤三,修改主配置文件,关联上面的实体配置文件。

>>步骤四,编写测试类,OneToManyTest.java内容(省略导入的包)如下:

package com.asm.hibernate.test;   
public class OneToManyTest {   
    public static void main(String[] args) {   
        add();   
        query(1);   
    }   
    static Department query(int departId) {   
        Session s = null;   
        try {   
            s = HibernateUtil.getSession();   
            Department depart = (Department) s.get(Department.class, departId);   
            System.out.println("employee size:" + depart.getEmps().size());   
            return depart;   
        } finally {   
            if (s != null)   
                s.close();   
        }   
    }   
    static void add() {   
        Session s = null;   
        Transaction tx = null;   
        try {   
            Department depart = new Department();   
            depart.setName("departName");   
  
            Employee emp1 = new Employee();   
            emp1.setName("empName1");   
            emp1.setDepart(depart);   
            Employee emp2 = new Employee();   
            emp2.setName("empName2");   
            emp2.setDepart(depart);   
  
            // Set<Employee> emps = new HashSet<Employee>();   
            // emps.add(emp1);   
            // emps.add(emp2);   
            // depart.setEmps(emps);   
  
            s = HibernateUtil.getSession();   
            tx = s.beginTransaction();   
            s.save(depart);   
            s.save(emp1);   
            s.save(emp2);   
            tx.commit();   
        } finally {   
            if (s != null)   
                s.close();   
        }   
    }   
}

说明:此类比较简单,增加两个员工信息,然后查出,同样可以体现出这种查询的方便,可以查看控制台,发现实质也是进行了两次查询操作。特别注意,上面注释掉的内容,思考怎样实现映射?如果加上注释掉的内容将会在控制台增加两条更新操作(注意更新的内容)。实际上注释掉的内容和已有内容建立了两种关联:“多对一”、“一对多”。