springboot整合mybatis-plus实现简答crud以及wrapper查询

本文主要是介绍springboot整合mybatis-plus实现简答crud以及wrapper查询,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述
在这里插入图片描述

1.导入pom依赖

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.5</version>
</dependency>

2.配置application.yml

spring:server:port: 8888datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:33060/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghaidriver-class-name: com.mysql.cj.jdbc.Driverprofiles:active: dev  # 设置项目的开发环境mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 设置日志为控制台输出# 配置逻辑删除global-config:db-config:logic-delete-value: 1 # 删除的值为1logic-not-delete-value: 0 # 不删除的值为0

3.编写MybatisPlusConfig配置类

包含:分页插件,乐观锁插件,逻辑删除,SQL执行效率插件

@Configuration  //配置类
@MapperScan("com.kuang.mapper")  //扫描mapper包
@EnableTransactionManagement  //开启事务
public class MybatisPlusConfig {//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();
}//分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();
}//逻辑删除
@Bean
public ISqlInjector sqlInjector() {return new LogicSqlInjector();
}//SQL执行效率插件
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();performanceInterceptor.setMaxTime(1000);  //单位ms,设置最大执行时间,超时则不执行performanceInterceptor.setFormat(true);  //格式化SQLreturn performanceInterceptor;
}

}

3.编写实体类

public class User {@TableId(type = IdType.INPUT)  //对应数据库中的自增  默认为ID_WORKER, 全局唯一,雪花算法private Long id;private String name;private Integer age;private String email;@TableLogic //逻辑删除
private Integer deleted;@Version  //乐观锁version注解
private Integer version;//字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

}

4.编写填充策略类(自动填充数据表中的属性)

@Component
public class MyMetaObjectHandler  implements MetaObjectHandler {//插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);
}//更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime",new Date(),metaObject);}

}

5.编写mapper类(继承BaseMapper就完事了)

@Repository
public interface UserMapper extends BaseMapper<User> {}

6,结束了,可以用了

下面mybatis-plus的常用方法

1.mapper类中常用方法

//查询全部
userMapper.selectList(null);
//根据id查询
userMapper.selectById(1l);
//批量查询
userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
//分页查询
Page<User> userPage = new Page<>(1,5);
IPage<User> page = userMapper.selectPage(userPage, null);
//插入
userMapper.insert(user);   
//更新
userMapper.update(user, null);
userMapper.updateById(user);//根据map删除
HashMap<String, Object> map = new HashMap<>();
map.put("name","张三");
userMapper.deleteByMap(map);
//删除
userMapper.deleteById(6l);  //配置逻辑删除后,删除操作为更新语句,将deleted更新为1

2.条件查询,wrapper

//查询email,name不为空,年龄大于18的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("email").isNotNull("name").ge("age", 18);  //年龄>=18
userMapper.selectList(wrapper).forEach(System.out::println);//查询名字为Tom的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "Tom");  
User user = userMapper.selectOne(wrapper);
System.out.println(user);//查询年龄在18,22之间的用户,根据id排序
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age", 18, 22).orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);//直接写SQL查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id < 4");
userMapper.selectObjs(wrapper).forEach(System.out::println);

3.mybatis-plus代码自动生成工具类

public class MysqlGenerator {public static void main(String[] args) {//代码自动生成器对象AutoGenerator generator = new AutoGenerator();//1.全局配置GlobalConfig gc = new GlobalConfig();String path = System.getProperty("user.dir");  //获取到项目根目录gc.setOutputDir(path+"/src/main/java");  //输出目录gc.setAuthor("cdd"); //设置作者gc.setOpen(true); //完成后打开文件夹gc.setFileOverride(false);  //是否覆盖
//        gc.setServiceName("%sService");  //去service的I前缀gc.setIdType(IdType.INPUT);  //设置而id的手动输入gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(true);   //支持swaggergenerator.setGlobalConfig(gc);//2.设置数据源DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:33060/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");dsc.setUsername("root");dsc.setPassword("root");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setDbType(DbType.MYSQL);generator.setDataSource(dsc);//3.包的配置PackageConfig pc = new PackageConfig();pc.setModuleName("mybatis_plus");pc.setParent("com.kuang");pc.setEntity("pojo");pc.setMapper("mapper");pc.setService("service");pc.setController("controller");generator.setPackageInfo(pc);//4.策略配置StrategyConfig strategy = new StrategyConfig();strategy.setInclude("user");  //设置要映射的表名strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);strategy.setEntityLombokModel(true);  //自动lombokstrategy.setLogicDeleteFieldName("deleted");  //逻辑删除字段//自动填充TableFill createTime = new TableFill("create_time", FieldFill.INSERT);TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);ArrayList<TableFill> tableFills = new ArrayList<>();tableFills.add(createTime);tableFills.add(updateTime);strategy.setTableFillList(tableFills);//乐观锁strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2  url采用下划线风格generator.setStrategy(strategy);generator.execute();
}
}

这篇关于springboot整合mybatis-plus实现简答crud以及wrapper查询的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/153410

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

MyBatis分页查询实战案例完整流程

《MyBatis分页查询实战案例完整流程》MyBatis是一个强大的Java持久层框架,支持自定义SQL和高级映射,本案例以员工工资信息管理为例,详细讲解如何在IDEA中使用MyBatis结合Page... 目录1. MyBATis框架简介2. 分页查询原理与应用场景2.1 分页查询的基本原理2.1.1 分