mybatis plus 配置LambdaQueryWrapper 添加sql查询条件
MyBatis Plus 提供了 LambdaQueryWrapper 类,使用它可以快速构建 SQL 查询条件。LambdaQueryWrapper 类的使用方法如下:
- 引入依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
- 配置 MyBatis Plus:
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
- 使用 LambdaQueryWrapper 构建查询条件:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findUsers(String name, Integer age) {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
// 添加查询条件
queryWrapper.like(StringUtils.isNotEmpty(name), User::getName, name)
.eq(age != null, User::getAge, age);
return userMapper.selectList(queryWrapper);
}
}
LambdaQueryWrapper 类的构造方法不需要传入实体类,只需要在调用查询条件的方法时传入实体类的属性即可。
LambdaQueryWrapper 类提供了多种查询条件的方法,如:eq、ne、gt、ge、lt、le、in、notIn、like、notLike、isNull、isNotNull、orderBy 等。
需要注意的是,在使用 LambdaQueryWrapper 类时,需要在实体类的属性上添加 @TableField 注解,否则无法识别属性名
原文地址: http://www.cveoy.top/t/topic/c4eM 著作权归作者所有。请勿转载和采集!