Linux 拨号vps windows公众号手机端

MyBatis关联查询怎么实现一对多映射

lewis 9年前 (2016-09-12) 阅读数 9 #程序编程
文章标签 mybatis

在MyBatis中,一对多关联查询可以通过使用嵌套查询或者使用resultMap的collection属性来实现。

  1. 嵌套查询: 在Mapper.xml文件中,可以使用嵌套查询来实现一对多关联查询。例如:
<select id="findUserById" parameterType="int" resultMap="userResultMap">
    SELECT * FROM user WHERE id = #{id}
</select>

<resultMap id="userResultMap" type="User">
    <result property="id" column="Id"/>
    <result property="name" column="Name"/>
    <collection property="orders" ofType="Order">
        <select id="findOrdersByUserId" parameterType="int" resultType="Order">
            SELECT * FROM orders WHERE user_id = #{id}
        </select>
    </collection>
</resultMap>
  1. 使用resultMap的collection属性: 另一种方法是使用resultMap的collection属性来实现一对多关联查询。例如:
<resultMap id="userResultMap" type="User">
    <result property="id" column="Id"/>
    <result property="name" column="Name"/>
    <collection property="orders" ofType="Order" resultMap="orderResultMap"/>
</resultMap>

<resultMap id="orderResultMap" type="Order">
    <result property="id" column="Id"/>
    <result property="name" column="Name"/>
</resultMap>

在查询用户的时候,可以一起查询出用户的订单信息,然后将订单信息映射到用户对象的orders属性中。这样就实现了一对多关联查询的映射。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门