mybatis-plus多表查询
时间: 2023-09-13 11:14:03 浏览: 120
支持连表查询的mybatis-plus
5星 · 资源好评率100%
MyBatis-Plus 是一款 MyBatis 的增强工具,在多表查询方面提供了许多便利的功能和API。
MyBatis-Plus 多表查询可以通过以下方式实现:
1. 使用 MyBatis-Plus 提供的 QueryWrapper 类,通过链式调用方法实现多表查询。例如:
```java
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("user.*", "order.*")
.eq("user.id", 1)
.eq("order.user_id", 1)
.orderByDesc("order.create_time");
List<Map<String, Object>> list = userMapper.selectMaps(queryWrapper);
```
2. 使用 MyBatis-Plus 提供的 @TableField 注解,在实体类中定义关联字段。例如:
```java
@Data
public class User {
private Long id;
private String name;
private Integer age;
@TableField(exist = false)
private List<Order> orders;
}
@Data
public class Order {
private Long id;
private Long userId;
private String orderNo;
}
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT user.*, order.* FROM user LEFT JOIN order ON user.id = order.user_id WHERE user.id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age"),
@Result(property = "orders", column = "id", many = @Many(select = "com.example.mapper.OrderMapper.selectByUserId"))
})
User selectWithOrders(Long id);
}
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
@Select("SELECT * FROM order WHERE user_id = #{userId}")
List<Order> selectByUserId(Long userId);
}
```
以上是两种常用的 MyBatis-Plus 多表查询方式,具体使用方式可以根据实际情况选择。
阅读全文