MyBatisPlus在springboot中的简单使用学习
MySql配置
springboot2.2后,使用com.mysql.cj.jdbc.Driver
我们来学习MyBatisPlus操作数据库的crud等操作:
@Data
public class User {
// 使用@TableId() 选择主键策略
@TableId(type = IdType.ASSIGN_UUID)
private Long id;
private String name;
private Integer age;
private String email;
}
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
application.properties文件:
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/user?serverTimezone=GMT%2B8
spring.datasource.username = root
spring.datasource.password = 1123
#logging.level.com.secbro.mapper=info
# 显示日志信息更全面
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void findAll() {
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
@Test
public void addUser() {
User user = new User();
user.setAge(33);
user.setEmail("lucy@163.com");
user.setName("lucy");
int insert = userMapper.insert(user);
System.out.println("insert: " + insert);
}
}
测试addUser()之后,数据库中的信息为:
id值是由MyBatisPlus自动生成的,19位。
主键策略
自动增长 UUID redis实现 MyBatisPlus自带策略 snowflake算法
// 使用@TableId() 选择主键策略
@TableId(type = IdType.ASSIGN_UUID)
private Long id;
MyBatisPlus的自动填充
public class User {
@TableId(type = IdType.ASSIGN_UUID)
private Long id;
private String name;
private Integer age;
private String email;
private Date createTime;
private Date updateTime;
}
@Test
public void addUser() {
User user = new User();
user.setAge(33);
user.setEmail("lucy@163.com");
user.setName("lucy");
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
int insert = userMapper.insert(user);
System.out.println("insert: " + insert);
}
使用MyBatisPlus,可以自动填充数据,不需要set到对象中。
MyBatisPlus实现乐观锁
乐观锁主要解决丢失更新的问题
如果不考虑事务隔离性,产生读问题:
- 脏读
- 不可重复读
- 幻读
写问题:
- 丢失更新问题(多个人同时修改同一条记录,最后提交的把之前的提交数据覆盖)
悲观锁:串行 一个事务执行完才能执行下一个事务
乐观锁
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;
@EnableTransactionManagement
@Configuration
@MapperScan("com.example.demo.mapper")
public class MyConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
@Test
public void addUser() {
User user = new User();
user.setAge(21);
user.setEmail("lilei@163.com");
user.setName("东方不败");
// user.setCreateTime(new Date());
// user.setUpdateTime(new Date());
int insert = userMapper.insert(user);
System.out.println("insert: " + insert);
}
@Test
public void updateUser() {
User user = new User();
user.setId(1492400254520332290L);
user.setEmail("hahaha@gmail.com");
int i = userMapper.updateById(user);
System.out.println(i);
}
// 测试乐观锁
@Test
public void optimisticLockerUpdateUser() {
User user = userMapper.selectById(1492451634891091970L);
user.setAge(200);
userMapper.updateById(user);
}
可以看到进行写操作后version被修改为2
MyBatisPlus简单查询
@Test
public void optimisticLockerUpdateUser() {
User user = userMapper.selectById(1492451634891091970L);
user.setAge(200);
userMapper.updateById(user);
}
@Test
public void selectBatch() {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4, 5));
System.out.println(users);
}
@Test
public void selectMap() {
Map<String, Object> map = new HashMap<>();
map.put("name", "Helen");
map.put("age", 16);
List<User> users = userMapper.selectByMap(map);
System.out.println(users);
}
MyBatisPlus实现分页
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor pageInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
@Test
public void page() {
Page<User> userPage = new Page<>(1, 3);
userMapper.selectPage(userPage, null);
System.out.println(userPage.getCurrent());
System.out.println(userPage.getRecords()); // 每页数据list集合
System.out.println(userPage.getSize()); // 每页显示记录数
System.out.println(userPage.getTotal()); // 总记录数
System.out.println(userPage.getPages()); // 总页数
System.out.println(userPage.hasNext());
System.out.println(userPage.hasPrevious());
}
MyBatisPlus删除
-
物理删除 真正删除
@Test public void delete() { int result = userMapper.deleteById(1492469422984663041L); System.out.println(result); }
-
逻辑删除 增加remove位标识是否被删除
@Test public void delete() { int result = userMapper.deleteById(1492469422984663041L); System.out.println(result); } @Test public void deleteBatch() { int result = userMapper.deleteBatchIds(Arrays.asList(2, 3)); System.out.println(result); }
MyBatisPlus条件查询
@Test
public void testSelectQuery() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
// ge gt le lt (大于等于 大于 小于等于 小于) eq ne (= <>)
// like 模糊查询 orderByDesc/Asc 排序
// last 语句最后拼接sql语句
// between 范围
// select 指定列
wrapper.ge("age", 20);
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}