在使用了Mybatis的基础上使用。
一、引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
二、application.yml中
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
三、service层
1、mapper接口中继承BaseMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
2、服务实现类继承ServiceImpl
public class UserService extends ServiceImpl<UserMapper,User> {
}
ServiceImpl里面的参数是实体类mapper和实体类
四、实用操作
这样之后可以直接调用MybatisPlus中许多内置的CRUD方法。
需要注意的是,在MybatisPlus中,插入和更新操作是被封装在一条指令中的。
@PostMapping
public boolean save(@RequestBody User user){
return userService.saveOrUpdate(user);
}
如果之前没有这条数据,就执行的insert操作,如果之前有这条数据,那么久更新这条数据。
底层实现:
public boolean saveOrUpdate(T entity) {
if (null == entity) {
return false;
} else {
TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass);
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!", new Object[0]);
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!", new Object[0]);
Object idVal = tableInfo.getPropertyValue(entity, tableInfo.getKeyProperty());
return !StringUtils.checkValNull(idVal) && !Objects.isNull(this.getById((Serializable)idVal)) ? this.updateById(entity) : this.save(entity);
}
如何实现分页查询
在实现分页查询之前需要书写一个配置类:
在根目录下写一个config包,其中新建一个MyubatisPlusConfig.java,用来实现分页的插件
@Configuration
@MapperScan("com.secure.mapper")
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
具体的实现如下:
```java
@GetMapping("/page")
public Page<User> findPage(
@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username
) {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like(Strings.isNotEmpty(username),"username",username)
.orderByDesc("id"); //按id从大到校倒序排列
return userService.page(new Page<>(pageNum, pageSize),wrapper);
}
从前端接受pageNum,pageSize和查询条件username,这里需要注意的是mp内置的条件封装器:wrapper,如果后面不填写就是无条件。
这里我采用的是精准查询的like方法,里面使用Strings的isNotEmpty方法保证查询条件不为空,和一个按照id从小到大的排序的orderByDesc方法。最后调用page方法把wrapper作为参数传进去。