Mybaits利用resultMap实现一对多

对于一对多的resultMap的定义
<resultMap type="dancheng.mybatis.po.Orders" id="OrderUserResultMap">
    <!-- 配置映射的订单信息 -->
    <id column="id" property="id" />
    <result column="user_id" property="userId" />
    <result column="number" property="number" />
    <result column="createtime" property="createtime" />
    <result column="note" property="note" />
    
    <!-- 配置映射关联信息 -->
    <!-- association:用于映射关联查询单个对象的信息 property:要将关联查询的用户信息映射到Orders中哪个属性 -->
    <association property="user" javaType="dancheng.mybatis.po.User">
        <!-- id:关联查询用户的唯一标识 -->
        <id column="user_id" property="id" />
        <result column="username" property="username" />
        <result column="sex" property="sex" />
        <result column="address" property="address" />
    </association>
</resultMap>

<!-- 查询订单及订单明细的resultMap -->
<resultMap type="dancheng.mybatis.po.Orders" id="OrderAndOrderDetailResultMap" extends="OrderUserResultMap">
    <!-- 订单信息 -->
    <!-- 用户信息 -->
    
    <!-- 订单明细信息
        一个订单关联查询出了多条明细 ,要是用collocation进行映射
        collocation:对关联查询到的多条记录映射到集合对象中
        porperty:将关联查询到多条记录映射到dancheng.mybatis.po.Orders的哪个属性
        ofType:指定映射到list集合属性中pojo的类型
     -->
     <collection property="orderdetails" ofType="dancheng.mybatis.po.Orderdetail">
         <!-- 订单明细的唯一标识  -->
         <id column="id" property="id"/>
         <result column="items_id" property="itemsId"/>
         <result column="items_num" property="itemsNum"/>
         <result column="orders_id" property="ordersId"/>
     </collection>
    
</resultMap>


调用resultMap
<select id="findOrderAndOrderDetailResultMap" resultMap="OrderAndOrderDetailResultMap">
    SELECT
        orders.*,
        user.username,
        user.sex,
        user.address,
        orderdetail.*
    FROM orders,
        USER,
        orderdetail
    WHERE orders.user_id = user.id AND orderdetail.orders_id = orders.id
</select>


mapper中的接口
public List<Orders> findOrderAndOrderDetailResultMap() throws Exception;


Test
public class OrdersMapperCustomTest {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void setUp() throws Exception {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
    
    @Test
    public void testFindOrderAndOrderDetailResultMap() throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
        
        List<Orders> orderList = ordersMapperCustom.findOrderAndOrderDetailResultMap();
        
        System.out.println(orderList);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值