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

2024-04-20

在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属性中。这样就实现了一对多关联查询的映射。

《MyBatis关联查询怎么实现一对多映射.doc》

下载本文的Word格式文档,以方便收藏与打印。