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>
這些方法可以根據具體的業務需求來選擇使用,可以根據關聯關系的復雜程度和查詢性能來進行選擇。