1.定义mybatis-plus的配置文件
该配置文件主要是配置了自带的分页插件PaginationInnerInterceptor,同时把对dao的扫码路径也转移到该配置文件中,启动类的dao扫描就可以删除了。
@Configuration
@MapperScan("com.leeong.demo.dao")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor innerInterceptor = new PaginationInnerInterceptor();
innerInterceptor.setDbType(DbType.MYSQL);
interceptor.addInnerInterceptor(innerInterceptor);
return interceptor;
}
}
2. 定义入参对象UserDTO
UserDTO 继承 BaseDTO,BaseDTO 定义分页参数current和 size
@Data
public class BaseDTO {
/**
* 每页记录数
*/
public Integer size;
/**
* 当前是第几页
*/
public Integer current;
}
@Data
public class UserDTO extends BaseDTO implements Serializable {
private Long id;//主键ID
private String name;//名称
private Integer age;// 年龄
private Integer sex;// 性别
private Integer status;//状态
private Date createTime;// 创建时间
}
3.编写DemoService类
该类包含了分页、复杂条件查询两个方法。复杂条件查询包括=、>=、like、in、orderby 等。
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class MybatisPlusDemoService {
private UserDao userDao;
/**
* 根据条件查询user 列表
* 创建 lambad 表达式
* @param user
* @return
*/
public List<User> selectUserByCondition(UserDTO user){
List<User> list = userDao.selectList(getWrappersByCondtion(user));
return list;
}
/**
* 组装查询条件
* @param user
* @return
*/
private LambdaQueryWrapper<User> getWrappersByCondtion(UserDTO user){
LambdaQueryWrapper<User> condition = Wrappers.<User>query().lambda().
// age = user.getAge()
eq(user.getAge() != null, User::getAge, user.getAge()).
// status in(1,2) List<Integer> 集合也可以
in(User::getStatus, 1, 2).
// name like '王%'
likeRight(StringUtils.isNotBlank(user.getName()), User::getName, user.getName()).
// create_time >= user.getCreateTime
ge(user.getCreateTime() != null, User::getCreateTime, user.getCreateTime()).
// 按照创建时间倒序排列
orderByDesc(User::getCreateTime);
return condition;
}
/**
* 根据查询条件返回分页数据
* @param user
* @return
*/
public IPage<User> page(UserDTO user){
return userDao.selectPage(new Page<>(user.getCurrent(), user.getSize()),
getWrappersByCondtion(user));
}
}
4.UserController 增加分页和列表访问方法
@PostMapping("/user/list")
public Map<String,Object> list(@RequestBody UserDTO user){
Map<String,Object> map = new HashMap<>();
map.put("code",200);
map.put("data",mybatisPlusDemoService.selectUserByCondition(user));
return map;
}
@PostMapping("/user/page")
public Map<String,Object> page(@RequestBody UserDTO user){
Map<String,Object> map = new HashMap<>();
map.put("code",200);
map.put("data",mybatisPlusDemoService.page(user));
return map;
}
5.总结
在dao 和 mapper中不增加任何sql和方法的情况下实现了复杂条件查询和分页的功能,这样开发起来是不是更加的方便了呢。具体更多更复杂的操作可以直接访问mybatis-plus官网(https://baomidou.com/),提供了更加全面的使用案例。
源码地址