zoukankan      html  css  js  c++  java
  • 九、一对多

    三、一对多

    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还没有保存setse1,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>
  • 相关阅读:
    两个有序链表的合并
    Perl学习笔记
    生信-基本概念
    生信-序列比较dp[未完成]
    PAT 1091 Acute Stroke [难][bfs]
    PAT 1038 Recover the Smallest Number[dp][难]
    PAT 1078 Hashing[一般][二次探查法]
    PAT 1122 Hamiltonian Cycle[比较一般]
    PAT 1151 LCA in a Binary Tree[难][二叉树]
    PAT 1148 Werewolf
  • 原文地址:https://www.cnblogs.com/myz666/p/8425065.html
Copyright © 2011-2022 走看看