九、一对多
三、一对多
1.在Department里添加集合属性
private int id; private String name; private Set<Employee> emps;//表示这个部门所含有的员工
2.在Department.hbm.xml下添加映射
<set name="emps"> <key column="dept_id"></key> <!--<one-to-many class="com.myz.domain.Employee"/> --> <one-to-many class="Employee"/> </set>
3.测试
//取出所有部门编号为1的员工 Department department= (Department) session.get(Department.class, 1); Set<Employee> emps = department.getEmps(); for(Employee e:emps){ System.out.println(e.getName()); } //添加 Department department= new Department(); department.setId(2); department.setName("人事部"); Set<Employee> sets=new HashSet<Employee>(); Employee e1=new Employee(); e1.setName("李逵"); e1.setId(3); Employee e2=new Employee(); e1.setName("武松"); e2.setId(4); sets.add(e1); sets.add(e2); department.setEmps(sets); session.save(department);
执行这段代码可能会报错,因为在保存department的时候,hibernate还没有保存sets和e1,e2等对象。
如果发生了异常,在Department.hbm.xml的一对多中添加级联保存即可
<set name="emps" cascade="save-update"> <key column="dept_id"></key> <!--<one-to-many class="com.myz.domain.Employee"/> --> <one-to-many class="Employee"/> </set>