在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对象中返回。