在MyBatis中进行关联查询可以通过在Mapper文件中使用嵌套查询来实现。以下是一个简单的例子:
public class User {
private Long userId;
private String userName;
private List<Order> orders;
// getters and setters
}
public class Order {
private Long orderId;
private Long userId;
private String orderName;
// getters and setters
}
public interface UserMapper {
User getUserWithOrders(Long userId);
}
public interface OrderMapper {
List<Order> getOrdersByUserId(Long userId);
}
UserMapper.xml
<select id="getUserWithOrders" resultMap="userWithOrders" parameterType="java.lang.Long">
SELECT * FROM user WHERE user_id = #{userId}
</select>
<resultMap id="userWithOrders" type="User">
<id property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<collection property="orders" ofType="Order">
<id property="orderId" column="order_id"/>
<result property="orderName" column="order_name"/>
</collection>
</resultMap>
OrderMapper.xml
<select id="getOrdersByUserId" resultType="Order" parameterType="java.lang.Long">
SELECT * FROM order WHERE user_id = #{userId}
</select>
User user = userMapper.getUserWithOrders(1L);
这样就可以使用MyBatis进行关联查询了。需要注意的是,在配置文件中要正确配置Mapper接口和XML文件的对应关系。