在MyBatis中,可以使用collection嵌套查詢來實現(xiàn)一對多的關聯(lián)查詢。實現(xiàn)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;
}
}
通過以上步驟,就可以實現(xiàn)使用collection嵌套查詢來關聯(lián)查詢一對多的數(shù)據(jù)。在查詢用戶信息的同時,也可以查詢用戶的訂單信息,并將其封裝到User對象中返回。