mybatis-plus improves efficiency of CRUD operations
1. Auto-fill at code level
1. Add @TableField annotation to the entity class
The premise is that there are corresponding fields in your database, and there is no automatic filling setting, and then add @TableField annotations to the attributes that need to be filled
package com.hzxy.mybatisplus.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// 字段添加填充
@TableField(fill = FieldFill.INSERT)
private Date CreateTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date UpdateTime;
}
2. Write a custom processor
We need to write a custom processor to handle the filling content
package com.hzxy.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component //把处理器加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill .......");
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
// 更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill .......");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
3. Testing
@Test
public void testInsert(){
User user = new User();
user.setName("Ye");
user.setAge(18);
user.setEmail("[email protected]");
int result = userMapper.insert(user);
System.out.println(result);
System.out.println(user);
}
@Test
public void testUpdate(){
User user = new User();
user.setId(1364545190177611777L);
user.setName("Ye");
user.setAge(20);
user.setEmail("[email protected]");
int result = userMapper.updateById(user);
System.out.println(result);
System.out.println(user);
}
}
result:
2. Add SQL statement log
Add in the configuration
### 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
result:
3. Add optimistic lock plugin
1. Add @Version annotation to the entity class
Note that there must be corresponding fields in the database
package com.hzxy.mybatisplus.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@Version //乐观锁version注解
private Integer version;
// 字段添加填充
@TableField(fill = FieldFill.INSERT)
private Date CreateTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date UpdateTime;
}
2. Add configuration configuration class
We create a new configuration class and release the annotation of scanning Mapper to this class
package com.hzxy.mybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
// 扫描我们的 Mapper 文件夹
@MapperScan("com.hzxy.mybatisplus.mapper")
@EnableTransactionManagement
@Configuration //配置类
public class MybatisPlusConfig {
//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
3. Testing
First test
@Test
public void testOptimisticLocker(){
// 1. 查询用户信息
User user = userMapper.selectById(1L);
// 2. 修改用户信息
user.setName("ybg");
user.setEmail("[email protected]");
// 3. 执行更新操作
userMapper.updateById(user);
}
result:
Second test
@Test
public void testOptimisticLocker2(){
// 1. 查询用户信息
User user = userMapper.selectById(1L);
// 2. 修改用户信息
user.setName("ybg");
user.setEmail("[email protected]");
// 3. 执行更新操作
// 1. 查询用户信息
User user1 = userMapper.selectById(1L);
// 2. 修改用户信息
user.setName("dzy");
user.setEmail("[email protected]");
// 3. 执行更新操作
userMapper.updateById(user1);
userMapper.updateById(user);
}
result:
Note: The version is 4 because I executed it twice, the second screenshot!
4. Three query methods
// 通过id查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 批量查询
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1,2,3));
users.forEach(System.out::println);
}
// 条件查询之一map查询
@Test
public void testSelectByMap(){
HashMap<String,Object> map = new HashMap<>();
map.put("name","Ye");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
The result of the last query:
5. Paging query
1. Add the following code to the configuration class
// 分页拦截器
@Bean
public PaginationInterceptor paginationInnerInterceptor() {
return new PaginationInterceptor();
}
2. Testing
@Test
public void testPaginationInterceptor(){
// 参数一: 当前页
// 参数二: 页面大小
Page<User> page = new Page<>(2,2);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
result:
6. Three deletion methods
// 通过id删除
@Test
public void testDeleteById(){
userMapper.deleteById(1L);
}
// 批量删除
@Test
public void testDeleteByBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1,2,3));
}
// 条件删除之一map删除
@Test
public void testDeleteByMap(){
HashMap<String,Object> map = new HashMap<>();
map.put("name","Ye");
userMapper.deleteByMap(map);
}
The last deleted result:
7, logical deletion
1. Add @TableLogic annotation to the entity class
Note that there must be corresponding fields in the database
@TableLogic //逻辑删除
private Integer deleted;
2. Add configuration
Configuration file
### 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
Configuration class
// 逻辑删除组件
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
3. Testing
Although it is still a deletion method, it actually uses logical deletion
// 通过id删除
@Test
public void testDeleteById(){
userMapper.deleteById(1L);
}
Result:
Test the query again
// 通过id查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
Result: After the
logical deletion, the query is not available, but the database still has this data.