mybatis中one2many

來源:互聯網
上載者:User

標籤:style   color   使用   os   art   問題   

上一章講了many2one,接下來看看單向的one2many,請注意,下面的代碼只做示範,不推薦在真實項目中使用。通過這個例子,也能更深刻的理解到在使用mybatiis的時候,應該更加謹慎的設計對象。
首先建立對象:
public class Employee {
    private Long id;
    private String name;
}
public class Department {
    private Long id;
    private String name;
    private Set<Employee> emps = new HashSet<Employee>();
}
可以看到department和employee是單向的one2many。
這時候,對於employee來說,就是一個簡單的單對象,我們先完成Employee對象的映射:
<mapper namespace="cd.itcast.mybatis.mapper.EmployeeMapper">

    <insert id="save" parameterType="Employee" useGeneratedKeys="true"
keyProperty="id">
        INSERT INTO EMPLOYEE(name)
        VALUES
        (#{name})
    </insert>

    <select id="get" resultType="Employee" parameterType="long">
        SELECT * FROM
        EMPLOYEE WHERE id = #{id}
    </select>
</mapper>
接下來看看department的映射。先看儲存。注意,之前我們說過,在mybatis中,所有的sql都是我們自己來控制。而現在的對象是單向的one2many,考慮在hibernate中,因為從many方沒法管理one方的關係,只有one方能夠管理關聯性,所以只有通過額外的update語句來完成關係的維護。所以,現在我們除了department本身的儲存,還需要用一個額外的update來維護one和many的關係:
<insert id="save" parameterType="Employee" useGeneratedKeys="true"
keyProperty="id">
    INSERT INTO DEPARTMENT(name)
    VALUES
    (#{name})
</insert>

<update id="update" parameterType="hashmap">
    UPDATE EMPLOYEE SET DEPT_ID = #{deptId} WHERE id = #{id}
</update>
Insert沒啥多說的,注意這個update,我們設定的parameterType是hashmap類型。下面的update語句中,使用了#{deptid}和#{id},在這裡deptid和id就不再指代屬性了,而是map中的key值了。
下面來看看save測試:
@Test
public void testSave() {
    Department d = new Department();
    d.setName("d");

    Employee e = new Employee();
    e.setName("e1");

    Employee e2 = new Employee();
    e2.setName("e2");

    d.getEmps().add(e);
    d.getEmps().add(e2);

    SqlSession session = MyBatisUtil.getInstance().openSession();

    EmployeeMapper em = session.getMapper(EmployeeMapper.class);
    em.save(e);
    em.save(e2);

    DepartmentMapper dm = session.getMapper(DepartmentMapper.class);
    dm.save(d);

    for (Employee te : d.getEmps()) {
    Map<String, Object> m = new HashMap<String, Object>();
    m.put("deptId", d.getId());
    m.put("id", te.getId());
    dm.update(m);
}

    session.commit();
    session.close();
}

一定要注意儲存順序,首先是儲存many方的兩個employee,接著儲存one方,department,然後我們需要手動遍曆department對應的employee列表,並建立成一個一個的hashmap,並將這些hashmap作為參數傳入更新關係的update中。
從這個save就可以看出,如果對象設計有問題,那麼在設計sql的時候就很困難。當然,還有其他的簡單的儲存方式,比如儲存employee的時候使用hashmap儲存,不使用Employee對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.