在MyBatis中,可以使用collection嵌套查詢來實現一對多的關聯查詢。實現collection嵌套查詢的步驟如下:
public interface UserMapper {
User selectUserById(Integer userId);
List<Order> selectOrdersByUserId(Integer userId);
}
<!-- 查詢用戶信息 -->
<select id="selectUserById" parameterType="int" resultType="User">
SELECT * FROM user WHERE id = #{userId}
</select>
<!-- 查詢用戶的訂單信息 -->
<select id="selectOrdersByUserId" parameterType="int" resultType="Order">
SELECT * FROM orders WHERE user_id = #{userId}
</select>
public class User {
private Integer id;
private String name;
private List<Order> orders;
// getters and setters
}
<!-- 查詢用戶信息及其訂單信息 -->
<select id="selectUserById" parameterType="int" resultType="User">
SELECT * FROM user WHERE id = #{userId}
</select>
<resultMap id="userMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="orders" ofType="Order">
<result column="order_id" property="orderId"/>
<result column="order_name" property="orderName"/>
</collection>
</resultMap>
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Integer userId) {
User user = userMapper.selectUserById(userId);
List<Order> orders = userMapper.selectOrdersByUserId(userId);
user.setOrders(orders);
return user;
}
}
通過以上步驟,就可以實現使用collection嵌套查詢來關聯查詢一對多的數據。在查詢用戶信息的同時,也可以查詢用戶的訂單信息,并將其封裝到User對象中返回。