mybatis-plus实现多表查询
时间: 2023-04-29 10:01:13 浏览: 127
Mybatis-Plus可以通过注解或XML配置文件实现多表查询。以下是一个简单的例子:
1. 定义实体类
假设我们有两个表:user和order,它们之间是一对多的关系。我们需要查询user表中的所有用户以及他们的订单信息。首先我们需要定义两个实体类:
```java
@Data
public class User {
private Long id;
private String name;
private Integer age;
private List<Order> orders;
}
@Data
public class Order {
private Long id;
private Long userId;
private String orderNo;
private BigDecimal amount;
}
```
2. 定义Mapper接口
接下来我们需要定义Mapper接口,使用@Mapper注解标记该接口,并继承BaseMapper接口。在该接口中定义一个方法,使用@Select注解指定SQL语句,使用@Results注解指定结果集映射关系。
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT u.*, o.id as order_id, o.order_no, o.amount FROM user u LEFT JOIN order o ON u.id = o.user_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"))
})
List<User> selectWithOrders();
}
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
@Select("SELECT * FROM order WHERE user_id = #{userId}")
List<Order> selectByUserId(Long userId);
}
```
3. 调用Mapper方法
最后,在Service或Controller中调用Mapper方法即可:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getUsersWithOrders() {
return userMapper.selectWithOrders();
}
}
```
这样就可以查询出所有用户以及他们的订单信息了。
阅读全文