欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

MyBatisPlus在SpringBoot中的简单使用

时间:2023-06-14
MyBatisPlus在springboot中的简单使用学习

MySql配置

springboot2.2后,使用com.mysql.cj.jdbc.Driver

我们来学习MyBatisPlus操作数据库的crud等操作:

@Datapublic 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;@Repositorypublic interface UserMapper extends baseMapper {}

@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.Driverspring.datasource.url = jdbc:mysql://localhost:3306/user?serverTimezone=GMT%2B8spring.datasource.username = rootspring.datasource.password = 1123#logging.level.com.secbro.mapper=info# 显示日志信息更全面mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

@SpringBootTestpublic class DemoApplicationTests {@Autowiredprivate UserMapper userMapper;@Testpublic void findAll() {List users = userMapper.selectList(null);System.out.println(users);}@Testpublic 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;}

@Testpublic 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; }}

@Testpublic 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);}@Testpublic void updateUser() { User user = new User(); user.setId(1492400254520332290L); user.setEmail("hahaha@gmail.com"); int i = userMapper.updateById(user); System.out.println(i);}// 测试乐观锁@Testpublic void optimisticLockerUpdateUser() { User user = userMapper.selectById(1492451634891091970L); user.setAge(200); userMapper.updateById(user);}

可以看到进行写操作后version被修改为2

MyBatisPlus简单查询

@Testpublic void optimisticLockerUpdateUser() { User user = userMapper.selectById(1492451634891091970L); user.setAge(200); userMapper.updateById(user);}@Testpublic void selectBatch() { List users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4, 5)); System.out.println(users);}@Testpublic void selectMap() { Map map = new HashMap<>(); map.put("name", "Helen"); map.put("age", 16); List users = userMapper.selectByMap(map); System.out.println(users);}

MyBatisPlus实现分页

@Beanpublic MybatisPlusInterceptor pageInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2)); return interceptor;}

@Testpublic void page() { Page 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删除

物理删除 真正删除

@Testpublic void delete() { int result = userMapper.deleteById(1492469422984663041L); System.out.println(result);}

逻辑删除 增加remove位标识是否被删除

@Testpublic void delete() { int result = userMapper.deleteById(1492469422984663041L); System.out.println(result);}@Testpublic void deleteBatch() { int result = userMapper.deleteBatchIds(Arrays.asList(2, 3)); System.out.println(result);}

MyBatisPlus条件查询

@Testpublic void testSelectQuery() { QueryWrapper wrapper = new QueryWrapper<>(); // ge gt le lt (大于等于 大于 小于等于 小于) eq ne (= <>) // like 模糊查询 orderByDesc/Asc 排序 // last 语句最后拼接sql语句 // between 范围 // select 指定列 wrapper.ge("age", 20); List users = userMapper.selectList(wrapper); System.out.println(users);}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。