mybatisplus怎么三表联查
时间: 2023-10-06 12:13:41 浏览: 83
Mybatis Plus支持使用注解或XML配置实现三表联查。以下是使用注解实现三表联查的示例:
假设有三个表:user、order和order_item,它们的关系是:user和order是一对多的关系,order和order_item是一对多的关系。
1. 在UserMapper接口中添加方法:
```
@Select("SELECT u.*, o.*, oi.* FROM user u LEFT JOIN order o ON u.id = o.user_id LEFT JOIN order_item oi ON o.id = oi.order_id WHERE u.id = #{userId}")
List<Map<String, Object>> getUserOrderItem(Long userId);
```
2. 在OrderMapper接口中添加方法:
```
@Select("SELECT o.*, oi.* FROM order o LEFT JOIN order_item oi ON o.id = oi.order_id WHERE o.user_id = #{userId}")
List<Map<String, Object>> getOrderItem(Long userId);
```
3. 在OrderItemMapper接口中添加方法:
```
@Select("SELECT * FROM order_item WHERE order_id = #{orderId}")
List<OrderItem> getByOrderId(Long orderId);
```
4. 在UserService中调用方法:
```
public List<User> getUserOrderItem(Long userId) {
List<Map<String, Object>> result = userMapper.getUserOrderItem(userId);
Map<Long, User> userMap = new HashMap<>();
Map<Long, Order> orderMap = new HashMap<>();
List<OrderItem> orderItemList = new ArrayList<>();
for (Map<String, Object> map : result) {
Long userId = Long.valueOf(map.get("id").toString());
User user = userMap.get(userId);
if (user == null) {
user = new User();
user.setId(userId);
user.setUsername(map.get("username").toString());
userMap.put(userId, user);
}
Long orderId = Long.valueOf(map.get("o_id").toString());
Order order = orderMap.get(orderId);
if (order == null) {
order = new Order();
order.setId(orderId);
order.setUserId(userId);
order.setOrderNo(map.get("order_no").toString());
orderMap.put(orderId, order);
}
OrderItem orderItem = new OrderItem();
orderItem.setId(Long.valueOf(map.get("oi_id").toString()));
orderItem.setOrderId(orderId);
orderItem.setProductNo(map.get("product_no").toString());
orderItem.setQuantity(Integer.valueOf(map.get("quantity").toString()));
orderItemList.add(orderItem);
}
List<User> userList = new ArrayList<>(userMap.values());
for (User user : userList) {
List<Order> orderList = new ArrayList<>();
for (Order order : orderMap.values()) {
if (order.getUserId().equals(user.getId())) {
List<OrderItem> oiList = new ArrayList<>();
for (OrderItem oi : orderItemList) {
if (oi.getOrderId().equals(order.getId())) {
oiList.add(oi);
}
}
order.setOrderItemList(oiList);
orderList.add(order);
}
}
user.setOrderList(orderList);
}
return userList;
}
```
此时,调用getUserOrderItem方法可以获得一个User对象,其中包含该用户的所有订单以及每个订单的商品项。
阅读全文