-
目录
#分页查询: 记得在启动类上加@MapperScan 注解, 指定扫描的包
#使用MybatisPlus的AutoGenerator插件生成代码文件
-
#简介
- Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。
- https://mp.baomidou.com/guide/config.html#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
-
#特性
-
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操
作,更有强大的条件构造器,满足各类使用需求
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、 SQLServer 等多种数据库
支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美
解决主键问题
支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD
操作
支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
支持关键词自动转义:支持数据库关键词(order、key......)自动转义,还可自定义关键词
内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代
码,支持模板引擎,更有超多自定义配置等您来使用
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通
List 查询
内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击
-
-
#初始数据库:
-
CREATE TABLE `user` ( `id` bigint(20) NOT NULL COMMENT '主键ID', `name` varchar(30) DEFAULT NULL COMMENT '姓名', `age` int(11) DEFAULT NULL COMMENT '年龄', `email` varchar(50) DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- 插入数据 INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('1', 'Jone', '18', 'test1@baomidou.com'); INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('2', 'Jack', '20', 'test2@baomidou.com'); INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('3', 'Tom', '28', 'test3@baomidou.com'); INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('4', 'Sandy', '21', 'test4@baomidou.com'); INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('5', 'Billie', '24', 'test5@baomidou.com');
-
-
#pom
-
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> </parent> <groupId>mybatisplus</groupId> <artifactId>mybatis-plus</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--mybatis-plus的springboot支持--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--简化代码的工具包--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> <version>1.18.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
-
-
#log4j.xml
-
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <param name="Encoding" value="UTF-8" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="info" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration>
-
-
#jdbc.properties
-
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///数据库名?useUnicode=true&characterEncoding=utf8 jdbc.username=# jdbc.password=#
-
-
#mybatis-config.xml
-
因为是与spring整合,所有mybatis-plus的大部分都写在spring的配置文件中,这里定义一个空的mybatis-config.xml即可
-
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
-
-
#BaseMapper
-
在MybatisPlus中,BaseMapper中定义了一些常用的CRUD方法,当我们自定义的Mapper接口继承BaseMapper后即可拥有了这些方法。
-
import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Constants; import org.apache.ibatis.annotations.Param; import java.io.Serializable; import java.util.Collection; import java.util.List; /*** <p> * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能 * </p> * <p> * 这个 Mapper 支持 id 泛型 * </p> ** @author hubin * @since 2016-01-23 */ public interface BaseMapper<T> { /*** <p> * 插入一条记录 * </p> ** @param entity 实体对象 */ int insert(T entity); /*** <p> * 根据 ID 删除 * </p> ** @param id 主键ID */ int deleteById(Serializable id); /*** <p> * 根据 columnMap 条件,删除记录 * </p> ** @param columnMap 表字段 map 对象 */ int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /*** <p> * 根据 entity 条件,删除记录 * </p> ** @param queryWrapper 实体对象封装操作类(可以为 null) */ int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /*** <p> * 删除(根据ID 批量删除) * </p> ** @param idList 主键ID列表(不能为 null 以及 empty) */ int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /*** <p> * 根据 ID 修改 * </p> ** @param entity 实体对象 */ int updateById(@Param(Constants.ENTITY) T entity); /*** <p> * 根据 whereEntity 条件,更新记录 * </p> ** @param entity 实体对象 (set 条件值,不能为 null) * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)*/ int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper); /*** <p> * 根据 ID 查询 * </p> ** @param id 主键ID */ T selectById(Serializable id); /*** <p> * 查询(根据ID 批量查询) * </p> ** @param idList 主键ID列表(不能为 null 以及 empty) */ List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /*** <p> * 查询(根据 columnMap 条件) * </p> ** @param columnMap 表字段 map 对象 */ List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /*** <p> * 根据 entity 条件,查询一条记录 * </p> ** @param queryWrapper 实体对象 */ T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /*** <p> * 根据 Wrapper 条件,查询总记录数 * </p> ** @param queryWrapper 实体对象 */ Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /*** <p> * 根据 entity 条件,查询全部记录 * </p> ** @param queryWrapper 实体对象封装操作类(可以为 null) */ List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /*** <p> * 根据 Wrapper 条件,查询全部记录 * </p> ** @param queryWrapper 实体对象封装操作类(可以为 null) */ List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /*** <p> * 根据 Wrapper 条件,查询全部记录 * 注意: 只返回第一个字段的值 * </p> ** @param queryWrapper 实体对象封装操作类(可以为 null) */ List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /*** <p> * 根据 entity 条件,查询全部记录(并翻页)* </p> ** @param page 分页查询条件(可以为 RowBounds.DEFAULT) * @param queryWrapper 实体对象封装操作类(可以为 null) */ IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /*** <p> * 根据 Wrapper 条件,查询全部记录(并翻页) * </p> ** @param page 分页查询条件 * @param queryWrapper 实体对象封装操作类 */ IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); }
-
-
#实体类注解:
-
@Data @TableName(value = "tb_employee")//指定表名 public class User{ //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value @TableId(value = "id",type = IdType.AUTO)//指定自增策略 private Integer id; //若没有开启驼峰命名,或者表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列 //@TableField(value = "last_name",exist = true) //private String lastName; private String name; private Integer age; private String email; }
-
-
#interface
-
@mapper public interface UserMapper extends BaseMapper<User> { }
-
-
#分页查询: 记得在启动类上加@MapperScan 注解, 指定扫描的包
-
/** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } /** * 逻辑删除 * */ @Bean public ISqlInjector sqlInjector(){ return new LogicSqlInjector(); } /** * SQL执行效率插件 设置 dev test 环境开启 */ @Bean public PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); }
-
-
#main方法上面要加 @MapperScan({"com.service.main.interfaces"}) 扫描注解
-
#配置
- 虽然在MybatisPlus中可以实现零配置,但是有些时候需要我们自定义一些配置,就需要使用Mybatis原生的一些配置文件方式了。
-
# 指定全局配置文件 mybatis-plus.config-location = classpath:mybatis-config.xml # 指定mapper.xml文件 mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
-
- 虽然在MybatisPlus中可以实现零配置,但是有些时候需要我们自定义一些配置,就需要使用Mybatis原生的一些配置文件方式了。
-
#测试案例:
-
import cn.itcast.mybatisplus.pojo.User; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class UserMaperTest { @Autowired private UserMapper userMapper; @Test public void testSelect(){ List<User> users = this.userMapper.selectList(null); for (User user : users) { System.out.println(user); } } @Test public void testSelectById(){ User user = this.userMapper.selectById(3L); System.out.println(user); } @Test public void testSelectByLike(){ QueryWrapper<User> wrapper = new QueryWrapper<User>(); wrapper.like("name", "o"); List<User> list = this.userMapper.selectList(wrapper); for (User user : list) { System.out.println(user); } } @Test public void testSelectByLe(){ QueryWrapper<User> wrapper = new QueryWrapper<User>(); wrapper.le("age", 20); List<User> list = this.userMapper.selectList(wrapper); for (User user : list) { System.out.println(user); } } @Test public void testSave(){ User user = new User(); user.setAge(25); user.setEmail("zhangsan@qq.com"); user.setName("zhangsan"); int count = this.userMapper.insert(user); System.out.println("新增数据成功! count => " + count); } @Test public void testDelete(){ this.userMapper.deleteById(7L); System.out.println("删除成功!"); } @Test public void testUpdate(){ User user = new User(); user.setId(6L); user.setName("lisi"); this.userMapper.updateById(user); System.out.println("修改成功!"); } @Test public void testSelectPage() { Page<User> page = new Page<>(2, 2); IPage<User> userIPage = this.userMapper.selectPage(page, null); System.out.println("总条数 ------> " + userIPage.getTotal()); System.out.println("当前页数 ------> " + userIPage.getCurrent()); System.out.println("当前每页显示数 ------> " + userIPage.getSize()); List<User> records = userIPage.getRecords(); for (User user : records) { System.out.println(user); } } }
-
-
#使用MybatisPlus的AutoGenerator插件生成代码文件
-
编写BasePojo文件
-
抽取公共的字段 根据自己的业务来抽取. 如果没有的话, 也可以不加
-
import lombok.Data; import java.util.Date; @Data public abstract class BasePojo implements java.io.Serializable { private Date created; private Date updated; }
-
-
-
增加模版依赖
-
<dependencies> <!-- freemarker 模板引擎 --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> </dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.7.1</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.0.7.1</version> </dependency>
-
-
编写CodeGenerator
-
参照官方文档案例改一下就ok了.
-
https://mp.baomidou.com/guide/generator.html
-
注意:
-
文档上写的目录 user.dir 是项目的根目录.
-
-
@EqualsAndHashCode(callSuper = true)
这个是自动生成equals和hashCode方法,我们一般不需要,所以将该注解去掉
- @Accessors(chain = true)
这个是表示,生成的set方法将采用链式编程方式,建议保留。
-
-
生成完实体之后,记得写指定 表名和主键id的注解.
-
注意int类型和布尔类型的值 是否正确. 数据库的int容易翻译成Boolean(可以在自定义中调整)
-
package com.service.main; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; import com.baomidou.mybatisplus.generator.config.rules.IColumnType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList; import java.util.List; /** * @program: service * @description: mybatis生成工具 * @author: 单人影 * @create: 2019-11-27 23:30 **/ public class MybatisGenerator { public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); //外层包名 String packageName = "com"; // 全局配置 GlobalConfig gc = new GlobalConfig(); //windows下生成文件的位置 final String projectPath = "D:\\myworkspace\\service\\service-baisc\\service-generator"; gc.setOutputDir(projectPath + "/src/main/java"); //是否覆盖文件 gc.setFileOverride(true); //生成文件的作者名称 gc.setAuthor("单人影"); gc.setOpen(false); gc.setActiveRecord(true); // XML 二级缓存 gc.setEnableCache(false); // XML ResultMap查询结果集字段 gc.setBaseResultMap(true); // XML columList(全表的字段) gc.setBaseColumnList(true); mpg.setGlobalConfig(gc); /** * 数据库配置 */ DataSourceConfig dsc = new DataSourceConfig(); //数据库连接 dsc.setUrl("jdbc:mysql://localhost:3306/service?useSSL=false&useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&autoReconnect=true&serverTimezone=GMT%2B8"); //设置数据库驱动,因为我的数据库版本是mysql5.7,所以使用该驱动 dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //mysql5.6以下的驱动 //dsc.setDriverName("com.mysql.jdbc.Driver"); //数据库名称 dsc.setUsername("root"); //数据库密码 dsc.setPassword("123456"); dsc.setTypeConvert(new MySqlTypeConvert() { // 自定义数据库表字段类型转换【可选】 public IColumnType processTypeConvert(String fieldType) { System.out.println("转换类型:" + fieldType); if (fieldType.toLowerCase().contains("tinyint")) { return DbColumnType.BOOLEAN; } return super.processTypeConvert(gc, fieldType); } }); mpg.setDataSource(dsc); /** * 包配置 */ final PackageConfig pc = new PackageConfig(); // 这里面会加上 上面的最外层包名 pc.setModuleName("service.example"); pc.setParent(packageName); mpg.setPackageInfo(pc); /** * 自定义配置 */ InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List<FileOutConfig> focList = new ArrayList<>(); /** * freemarker模版 /templates/mapper.xml.ftl * velocity模版 /templates/mapper.xml.vm */ focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { //自定义配置会被优先输出 @Override public String outputFile(TableInfo tableInfo) { //return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; //自定义输入文件名称 //结果: src/main/resources/mapper/UserInfoMapper.xml return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); /** * 策略配置 */ StrategyConfig strategy = new StrategyConfig(); // 表名生成策略 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); //要生成的表名 strategy.setInclude(new String[]{"cust_custinfo"}); //不配置默认会继承basemapper,会自动按照模版生成 //表名的前缀 // strategy.setTablePrefix(new String[]{"t_"}); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 // strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
-
-
-
#yml配置文件
-
server: port: 8090 spring: application: name: my-service datasource: name: datasource url: jdbc:mysql://localhost:3306/service?useSSL=false&useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&autoReconnect=true&serverTimezone=GMT%2B8 username: root password: 123456 # type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #mybatis-plus: # mapper-locations: classpath*:/mapper/*.xml # type-aliases-package: com.service.main.model #================================================= mybatis-plus start ================================================= mybatis-plus: global-config: db-config: id-type: auto # field-strategy: not_empty #驼峰下划线转换 # column-underline: false #逻辑删除配置 # logic-delete-value: 0 # logic-not-delete-value: 1 db-type: mysql refresh: false configuration: map-underscore-to-camel-case: true cache-enabled: false # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:mapper/custinfo/*.xml type-aliases-package: com.service.main.model # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段 call-setters-on-nulls: true #================================================= mybatis-plus end ===================================================
-
-
参数工具类:
-
前端代码:
-
//前端定义两个参数. 一个查询条件, 一个提交参数 query: { pageIndex: 1, pageSize: 10 }, searchParam: [ { column: 'creat_user', type: 'eq', value: '' }, { column: 'send_time', type: 'eq', value: '' }, { column: 'u_id', type: 'eq', value: localStorage.getItem('ms_uid') } ], //提交参数的时候 把条件封装一下,转成json字符串 提交的时候 传this.query for (const item of this.searchParam) { if (this.utils.isUndefined(this.query[item.column])) { continue; } item.value = this.query[item.column]; } this.query.conditionJson = JSON.stringify(this.searchParam);
-
-
后端代码:
-
处理条件工具类:
-
package com.danrenying.web.sendtips.utils; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.danrenying.web.sendtips.base.enums.MybatisEnum; import com.danrenying.web.sendtips.base.enums.ServiceCode; import com.danrenying.web.sendtips.base.exceptions.BusinessException; import com.danrenying.web.sendtips.base.utils.StringUtils; import com.danrenying.web.sendtips.model.ConditionVo; import java.util.List; /** * @program: 关联SQL工具类 * @description: * @author: 单人影 * @create: 2020/11/22 **/ public class SearchUtil { public static QueryWrapper parseWhereSql(String conditionJson) { QueryWrapper queryWrapper = new QueryWrapper(); if (StringUtils.isNotEmpty(conditionJson)) { List<ConditionVo> conditionList = JSON.parseArray(conditionJson, ConditionVo.class); if (CollectionUtils.isNotEmpty(conditionList)) { for (ConditionVo conditionVo : conditionList) { if (StringUtils.isEmpty(conditionVo.getValue())) { continue; } switch (MybatisEnum.getEnumByCode(conditionVo.getType())) { case eq: queryWrapper.eq(conditionVo.getColumn(), conditionVo.getValue()); break; case ne: queryWrapper.ne(conditionVo.getColumn(), conditionVo.getValue()); break; case like: queryWrapper.like(conditionVo.getColumn(), conditionVo.getValue()); break; case leftlike: queryWrapper.likeLeft(conditionVo.getColumn(), conditionVo.getValue()); break; case rightlike: queryWrapper.likeRight(conditionVo.getColumn(), conditionVo.getValue()); break; case notLike: queryWrapper.notLike(conditionVo.getColumn(), conditionVo.getValue()); break; case gt: queryWrapper.gt(conditionVo.getColumn(), conditionVo.getValue()); break; case lt: queryWrapper.lt(conditionVo.getColumn(), conditionVo.getValue()); break; case ge: queryWrapper.ge(conditionVo.getColumn(), conditionVo.getValue()); break; case le: queryWrapper.le(conditionVo.getColumn(), conditionVo.getValue()); break; default: throw new BusinessException(ServiceCode.MYBATIS_TYPE_ERROR); } } } } return queryWrapper; } }
-
-
封装实体类:
-
package com.danrenying.web.sendtips.model; import lombok.Data; import java.io.Serializable; @Data public class ConditionVo implements Serializable { /** * 数据库字段名 */ private String column; /** * 字段值 */ private String value; /** * 连接类型,如llike,equals,gt,ge,lt,le */ private String type; }
-
-
调用
-
QueryWrapper<SendMessageHistory> wrapper = SearchUtil.parseWhereSql(request.getConditionJson());
-
-
-
-
or 的使用
-
拼接条件的时候,and和or会出问题 比如下面这种 QueryWrapper<User> userWrapper = new QueryWrapper<User>(); userWrapper.eq("name", name); userWrapper.eq("pwd", pwd).or().eq("phone", phone); 这种写法拼出来的SQL语句是这样的 select * from user where (name = ? and pwd= ? or phone = ?) 正确的写法是这样的 QueryWrapper<User> userWrapper = new QueryWrapper<User>(); userWrapper.eq("name", name); userWrapper.and(wrapper -> wrapper.eq("pwd", pwd).or().eq("phone", phone)); select * from user where name = ? and ( pwd= ? or phone = ?)
-
-
条件参数:
-
查询方式 说明 setSqlSelect 设置 SELECT 查询字段 where WHERE 语句,拼接 + WHERE 条件
and AND 语句,拼接 + AND 字段=值
andNew AND 语句,拼接 + AND (字段=值)
or OR 语句,拼接 + OR 字段=值
orNew OR 语句,拼接 + OR (字段=值)
eq 等于= allEq 基于 map 内容等于= ne 不等于<> gt 大于> ge 大于等于>= lt 小于< le 小于等于<= like 模糊查询 LIKE notLike 模糊查询 NOT LIKE in IN 查询 notIn NOT IN 查询 isNull NULL 值查询 isNotNull IS NOT NULL groupBy 分组 GROUP BY having HAVING 关键词 orderBy 排序 ORDER BY orderAsc ASC 排序 ORDER BY orderDesc DESC 排序 ORDER BY exists EXISTS 条件语句 notExists NOT EXISTS 条件语句 between BETWEEN 条件语句 notBetween NOT BETWEEN 条件语句 addFilter 自由拼接 SQL last 拼接在最后,例如:last("LIMIT 1")
-
MyBatis-Plus
最新推荐文章于 2024-07-10 20:09:54 发布