mybatisplus 实现CURD

    技术2022-07-11  97

    一、 insert

    插入操作 @RunWith(SpringRunner.class) @SpringBootTest public class CRUDTests { @Autowired private UserMapper userMapper; @Test public void testInsert(){ User user = new User(); user.setName("Helen"); user.setAge(18); user.setEmail("55317332@qq.com"); int result = userMapper.insert(user); System.out.println(result); //影响的行数 System.out.println(user); //id自动回填 } }

    主键策略

    MyBatis-Plus默认的主键策略是:ID_WORKER 全局唯一ID

    **参考资料:分布式系统唯一ID生成方案汇总:**https://www.cnblogs.com/haoxinyue/p/5208136.html

    配置自增策略

    需要在创建数据表的时候设置主键自增

    实体字段中配置 @TableId(type = IdType.AUTO)

    @TableId(type = IdType.AUTO) private Long id;

    设置全局主键配置

    #全局设置主键生成策略 mybatis-plus.global-config.db-config.id-type=auto

    二、 update

    根据ID更新操作

    update时生成的sql自动是动态sql:UPDATE user SET age=? WHERE id=?

    @Test public void testUpdateById(){ User user = new User(); user.setId(1L); user.setAge(28); int result = userMapper.updateById(user); System.out.println(result); }

    自动填充

    填写创建时间 create_time,更新时间 update_time

    实体类添加注释

    @Data public class User { @TableField(fill = FieldFill.INSERT) private Date createTime; //@TableField(fill = FieldFill.UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; }

    ​ 实现对象处理器接口

    @Component public class MyMetaObjectHandler implements MetaObjectHandler { private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class); @Override public void insertFill(MetaObject metaObject) { LOGGER.info("start insert fill ...."); this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("updateTime", new Date(), metaObject); } @Override public void updateFill(MetaObject metaObject) { LOGGER.info("start update fill ...."); this.setFieldValByName("updateTime", new Date(), metaObject); } }

    乐观锁

    取出记录时,获取当前version更新时,带上这个version执行更新时, set version = newVersion where version = oldVersion如果version不对,就更新失败

    数据库添加version字段

    ALTER TABLE `user` ADD COLUMN `version` INT

    实体类添加version字段

    @Version @TableField(fill = FieldFill.INSERT) private Integer version;

    元对象处理器接口添加version的Insert 默认值

    @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("version", 1, metaObject); } 支持的数据类型只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime整数类型下 newVersion = oldVersion + 1newVersion 会回写到 entity 中仅支持 updateById(id) 与 update(entity, wrapper) 方法在 update(entity, wrapper) 方法下, wrapper 不能复用!!!

    注册Bean

    package com.atguigu.mybatisplus.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @Configuration @MapperScan("com.atguigu.mybatis_plus.mapper") public class MybatisPlusConfig { /** * 乐观锁插件 */ @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } }

    三、select

    根据ID查询记录

    @Test public void testSelectById(){ User user = userMapper.selectById(1L); System.out.println(user); }

    通过多个ID批量查询

    @Test public void testSelectBatchIds(){ List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3)); users.forEach(System.out::println); }

    简单条件查询

    @Test public void testSelectByMap(){ HashMap<String, Object> map = new HashMap<>(); map.put("name", "Helen"); map.put("age", 18); List<User> users = userMapper.selectByMap(map); users.forEach(System.out::println); } // map中的key对应的是数据库中的列名

    分页

    创建配置类

    /** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }

    四、 delete

    根据ID删除记录

    @Test public void testDeleteById(){ int result = userMapper.deleteById(8L); System.out.println(result); }

    批量删除

    @Test public void testDeleteBatchIds() { int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10)); System.out.println(result); }

    简单的条件查询删除

    @Test public void testDeleteByMap() { HashMap<String, Object> map = new HashMap<>(); map.put("name", "Helen"); map.put("age", 18); int result = userMapper.deleteByMap(map); System.out.println(result); }

    逻辑删除

    物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除数据逻辑删除:假删除,将对应数据中代表是否被删除字段状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录

    数据库添加delete 字段

    ALTER TABLE `user` ADD COLUMN `deleted` boolean

    实体类添加delete字段

    并加上 @TableLogic 注解 和 @TableField(fill = FieldFill.INSERT) 注解

    @TableLogic @TableField(fill = FieldFill.INSERT) private Integer deleted;

    元数据处理器添加delete的insert 默认值

    @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("deleted", 0, metaObject); }

    application.properties 加入配置

    mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0

    在 MybatisPlusConfig 中注册 Bean

    @Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); }

    五、 性能分析

    配置插件

    在 MybatisPlusConfig 中配置

    /** * SQL 执行性能分析插件 * 开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 */ @Bean @Profile({"dev","test"})// 设置 dev test 环境开启 public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(100);//ms,超过此处设置的ms则sql不执行 performanceInterceptor.setFormat(true); return performanceInterceptor; }

    SpringBoot 中设置dev 环境

    #环境设置:dev、test、prod spring.profiles.active=dev
    Processed: 0.011, SQL: 9