2018-02-16-3.mybatis一對多對映情況解析

weixin_33978044發表於2018-02-16

廢話不多說,直接上程式碼

(重點)UserMapper.xml檔案中關鍵對映程式碼,注意不能省略正常匹配的鍵,還有collection中使用ofType來通知型別

<resultMap id="queryUserWithOrders" type="User">
        <result column="user_id" property="id"/>
        <result column="username" property="username"/>
        <collection property="orders" ofType="Orders">
            <result column="number" property="number"/>
            <result column="id" property="id"/>
        </collection>
    </resultMap>
    <select id="queryUserWithOrders" resultMap="queryUserWithOrders">
      select
      u.username,
      o.*
      from `user` u
      LEFT JOIN orders o
      on u.id = o.user_id
    </select>

UserMapper.java介面程式碼

public interface UserMapper {

    User queryUserById(Integer id);

    List<User> queryUserByUsername(String name);


    public List<User> queryUserWithOrders();
}

pojo類User.java中程式碼:(增加一個orders並生成get和set方法,順便重寫了toString以便列印)

private List<Orders> orders;

    public List<Orders> getOrders() {
        return orders;
    }

    public void setOrders(List<Orders> orders) {
        this.orders = orders;
    }

相關文章