QueryWrapper实现关联查询
时间: 2023-07-31 15:08:53 浏览: 155
QueryWrapper 是 MyBatis-Plus 框架提供的一个查询构造器,它可以帮助我们方便地进行关联查询。
在 QueryWrapper 中实现关联查询有两种常见的方式:
1. 使用 Lambda 表达式
```java
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(User::getRole, "admin").eq(User::getIsDeleted, 0)
.nested(i -> i.eq(User::getRoleId, Role::getId).like(Role::getName, "管理员"));
List<User> userList = userMapper.selectList(queryWrapper);
```
2. 使用普通方式
```java
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user.role", "admin").eq("user.is_deleted", 0)
.nested(i -> i.eq("user.role_id", "role.id").like("role.name", "管理员"));
List<User> userList = userMapper.selectList(queryWrapper);
```
以上示例中,我们通过 `eq` 方法指定了主表和关联表之间的条件,通过 `nested` 方法可以实现嵌套查询,从而实现关联查询。其中,Lambda 表达式方式可读性更高,而普通方式更灵活。
需要注意的是,以上代码仅为示例,实际使用时需要根据具体的实体类和关联关系进行调整。同时,如果使用的是 MyBatis 原生的 XML 映射文件,还需要在 XML 文件中编写相应的 SQL 语句来实现关联查询。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)