Mybatis 关联查询(二

一对多的管理查询结果映射

  1、进行一对多的查询时候,要在主查询表对应的Po中加入关联查询表对应PO的类的list集合作为属性。

public class Orders {
    private Integer id;

    private Integer userId;

    private String number;

    private Date createtime;

    private String note;
    //订单明细
    private List<Orderdetail> orderdetails;
    public List<Orderdetail> getOrderdetails() {
        return orderdetails;
    }
......
}

  2、创建查询结果映射的resultMap

  <resultMap id="OrdersAndOrdertailResultMap" type="Orders" >
        <!--
          查询结果中唯一标识列的映射
          column:查询出来的列名
          property:po中的属性名称
      -->
        <id column="id" property="id"/>
        <!--
            查询结果中普通列的映射
            column:查询出来的列名
            property:po中的属性名称
        -->
        <result column="user_id" property="userId" />
        <result column="number" property="number" />
        <result column="createtime" property="createtime" />
        <result column="note" property="note" />
        <!--
            collection:该标签用来配置一对多的映射
            配置订单明细的映射信息
             property:要映射到的po类中的属性(orders中的属性)
            ofType:要映射到的那个po类(Orderdetail类)
        -->
        <collection property="orderdetails" ofType="Orderdetail" >
            <!--
         查询结果中唯一标识列的映射
         column:查询出来的列名
         property:po中的属性名称
     -->
            <id column="tail_id" property="id"/>
            <!--
                查询结果中普通列的映射
                column:查询出来的列名
                property:po中的属性名称
            -->
            <result column="id" property="ordersId" />
            <result column="items_id" property="itemsId" />
            <result column="items_num" property="itemsNum" />
        </collection>
    </resultMap>

  3. 编写mapper.xml

 <select id="findOrdersAndOrdertail" resultMap="OrdersAndOrdertailResultMap" >
        SELECT
            orders.*,
            orderdetail.id tail_id,
            orderdetail.items_id,
            orderdetail.items_num
        FROM
            orders,
            orderdetail
        WHERE
        orders.id = orderdetail.orders_id;
    </select>

  4. 编写mapper接口文件

public List<Orders> findOrdersAndOrdertail() throws Exception;

  5. 测试代码

 public void testFindOrdersAndOrdertail() throws Exception{
        SqlSession session = sessionFactory.openSession();
        Mapper mapper = session.getMapper(Mapper.class);
        List<Orders> orders = mapper.findOrdersAndOrdertail();
        for (Orders order : orders){
            System.out.println(order);
        }
    }

二、总结

  1. mybatis使用resultMap的collection对关联查询的多条记录映射到一个list集合属性中。

  2. 使用resultType实现:
    将订单明细映射到orders中的orderdetails中,需要自己处理,使用双重循环遍历,去掉重复记录,将订单明细放在orderdetails中。

posted @ 2017-07-30 22:09  一条路上的咸鱼  阅读(267)  评论(0编辑  收藏  举报