在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文件的對應關系。