1.数据表增加version字段
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`version` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
2.设置自动填充
package com.example.demo.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
import java.util.Date;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
@TableField(value = "version", fill = FieldFill.UPDATE)
private Integer version;
}
3.乐观锁插件
package com.example.demo.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper")
public class MyConfig {
/**
* 旧版本乐观锁插件
* @return
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
4.测试
package com.example.demo;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
// 查询操作
@Test
public void findAll() {
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
// 添加操作
@Test
public void testAdd() {
User user = new User();
user.setName("php");
user.setAge(20);
user.setEmail("123@qq.com");
int insert = userMapper.insert(user);
System.out.println(insert);
}
// 更新操作
@Test
public void testUpdate() {
User user = new User();
user.setId(1485617339597520897L);
user.setName("mybatis");
int i = userMapper.updateById(user);
System.out.println(i);
}
// 测试乐观锁
@Test
public void testOptimisticLocker() {
// 根据id查询
User user = userMapper.selectById(1485627449220710401L);
// 修改
user.setName("rust");
userMapper.updateById(user);
}
}
|