Mybatis提供了很好的支持来处理一对多查询问题。下面是一些处理一对多查询问题的方法:
<collection>
标签来定义一对多的关联关系。<resultMap id="userMap" type="User">
<id column="id" property="id" />
<result column="name" property="name" />
<collection property="orders" ofType="Order">
<id column="order_id" property="id" />
<result column="order_name" property="name" />
</collection>
</resultMap>
<select id="getUserWithOrders" resultMap="userMap">
SELECT u.id, u.name, o.id as order_id, o.name as order_name
FROM user u
LEFT JOIN order o ON u.id = o.user_id
WHERE u.id = #{id}
</select>
<association>
标签来定义关联对象,然后在关联对象的映射中使用<collection>
标签来定义关联的多个子对象。<resultMap id="userMap" type="User">
<id column="id" property="id" />
<result column="name" property="name" />
<association property="department" javaType="Department">
<id column="department_id" property="id" />
<result column="department_name" property="name" />
<collection property="employees" ofType="Employee">
<id column="employee_id" property="id" />
<result column="employee_name" property="name" />
</collection>
</association>
</resultMap>
<select id="getUserWithDepartmentAndEmployees" resultMap="userMap">
SELECT u.id, u.name, d.id as department_id, d.name as department_name, e.id as employee_id, e.name as employee_name
FROM user u
LEFT JOIN department d ON u.department_id = d.id
LEFT JOIN employee e ON d.id = e.department_id
WHERE u.id = #{id}
</select>
<select id="getUserWithOrders" resultType="User">
SELECT u.id, u.name, (SELECT o.id, o.name FROM order o WHERE o.user_id = u.id) as orders
FROM user u
WHERE u.id = #{id}
</select>
这些方法可以根据具体的业务需求来选择使用,可以根据关联关系的复杂程度和查询性能来进行选择。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: mybatis怎么用