1. 程式人生 > >MyBatis級聯多個物件屬性賦值

MyBatis級聯多個物件屬性賦值

一個客戶有多個訂單,   一個訂單對應一個客戶

需求:查詢一個使用者,得到對應的使用者及相關訂單

 

兩個實體類

package com.itlike.domain;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

@[email protected]@ToString
public class Customer {
    private Integer cust_id;
    private String cust_name;
    private String cust_profession;
    private String cust_phone;
    private String email;
    private List<Order> orders;
}
package com.itlike.domain;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@[email protected]@ToString
public class Order {
    private Integer order_id;
    private String order_name;
    private String order_num;
}

customermapper.xml中的結果屬性設定

級聯一個物件的屬性設定用association      

級聯多個物件的屬性設定用collection  

分步查詢也用collection

javatype 表明orders是一個list集合    oftype表明list集合中裝的都是  Order型別      

 <select id="getAllCustomers" resultMap="custMap">
        SELECT * from `customer` as c LEFT JOIN `order` as o ON c.cust_id=o.cust_id;
    </select>

    <resultMap id="custMap" type="Customer">
        <id column="cust_id" property="cust_id"/>
        <result column="cust_name" property="cust_name"/>
        <result column="cust_profession" property="cust_profession"/>
        <result column="cust_phone" property="cust_phone"/>
        <result column="email" property="email"/>

      <collection property="orders" javaType="list" ofType="Order">
          <id column="order_id" property="order_id"/>
          <result column="order_num" property="order_num"/>
          <result column="order_name" property="order_name"/>
      </collection>

    </resultMap>

和級聯一個物件使用association相同,查詢物件的自身屬性不能省略!!!