前几天运营提到说后台管理系统有几个地方想要模糊查询..

 

想了下是简单的,就是要注意以前方法的被调用情况,进行增量改动,以免牵一发而动全身。整理一波记录下(本次案例是按名字模糊查询学生信息)。

三种方式概览

  1. SQL 语句正常 like,service 层按需要添加 '%'
  2. SQL 使用 CONCAT 函数
  3. mybatis 的 bind 语法

依旧使用H2数据库(>>springboot与H2数据库快速本地测试),初始化脚本配置一个简单的学生表,添几条记录。

H2和mybatis相关配置

1)maven依赖

  1. <dependency>
  2. <groupId>com.h2database</groupId>
  3. <artifactId>h2</artifactId>
  4. <scope>runtime</scope>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.mybatis.spring.boot</groupId>
  8. <artifactId>mybatis-spring-boot-starter</artifactId>
  9. <version>2.0.1</version>
  10. </dependency>

2)application.properties

  1. server.port=8091
  2. server.servlet.context-path=/tsa
  3. #spring.datasource.url=jdbc:h2:mem:test
  4. spring.datasource.url=jdbc:h2:~/test
  5. spring.datasource.driver-class-name=org.h2.Driver
  6. spring.datasource.username=sa
  7. spring.datasource.password=123456
  8. spring.datasource.schema=classpath:h2sql/schema.sql
  9. spring.datasource.data=classpath:h2sql/data.sql
  10. spring.h2.console.enabled=true
  11. #localhost:8080/projectName/h2-console
  12. spring.h2.console.path=/h2-console
  13. #mybatis.config-location=classpath:/mybatis-config.xml
  14. mybatis.mapper-locations=classpath:/sqlmap/*Mapper.xml
  15. mybatis.configuration.map-underscore-to-camel-case=true
  16. mybatis.type-aliases-package=com.hwc.tsa.bean
  17. logging.level.com.hwc.tsa.dao=debug
  18. logging.level.com.hwc.tsa.mapper=debug

3)H2初始化脚本(学生表)

h2sql/schema.sql

  1. drop table if exists student;
  2. create table student(
  3. id int unsigned not null auto_increment comment '自增主键',
  4. name varchar(20) not null comment '字典类型-关联字段',
  5. age int unsigned not null comment '年龄',
  6.  
  7. status tinyint not null default 1 comment '逻辑删除字段',
  8. crt_time timestamp not null default CURRENT_TIMESTAMP comment '创建时间',
  9. upd_time timestamp default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP comment '更新时间',
  10.  
  11. PRIMARY KEY (id)
  12. );

h2sql/data.sql

  1. insert into student(name, age) values ('菠萝包', 1);
  2. insert into student(name, age) values ('皮卡丘', 3);
  3. insert into student(name, age) values ('悟空', 35);
  4. insert into student(name, age) values ('悟饭', 21);
  5. insert into student(name, age) values ('克林', 37);
  6. insert into student(name, age) values ('弗利沙', 999);
  7. insert into student(name, age) values ('妙蛙种子', 3);
  8. insert into student(name, age) values ('杰尼龟', 2);
  9. insert into student(name, age) values ('小杰', 17);

启动项目并检查项目结构

本次不是在之前的demo项目上继续的,只需关注几个目标包(xxx.bean.entity,xxx.mapper、resources/sqlmap、resources/h2sql)就OK。

1)先启动springboot项目,初始化H2数据库。

启动项目:

 

控制台连接H2数据库(>>springboot与H2数据库快速本地测试)检查数据初始化:

 

2)建立相应的包和目录结构,使用mybatis逆向工具快速生成entity和mapper

>>简单使用maven-mybatis插件逆向生成entity和Mapper

结构图:

 

方式1

方式1即 SQL 部分只写简单的 like,在 service 层决定哪个字段需要模糊查(加上 '%')。

StudentMapper 新增方法(按名字模糊查):

  1. /**
  2. * 表单模糊查询支持
  3. * @param record
  4. * @return
  5. */
  6. List<Student> selectByFormLikeSelective(Student record);

StudentMapper.xml 新增查询映射点:

  1. <select id="selectByFormLikeSelective" parameterType="student" resultMap="BaseResultMap">
  2. select <include refid="Base_Column_List"/> from student
  3. <where>
  4. <if test="name!=null and name!=''">
  5. and name like #{name}
  6. </if>
  7. <if test="status!=null">
  8. and status = #{status}
  9. </if>
  10. </where>
  11. </select>

编写测试类:

  1. @RunWith(SpringRunner.class)
  2. //不加载web环境,更快捷测试
  3. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
  4. //@SpringBootTest
  5. public class MapperDaoTests {
  6. private static final Logger logger = LoggerFactory.getLogger(MapperDaoTests.class);
  7.  
  8. @Autowired
  9. StudentMapper stuMapper;
  10.  
  11. @Test
  12. public void testStudentMapperLikeSelective() {
  13. //模拟controller输入
  14. Map<String, Object> map = new HashMap<>();
  15. map.put("name", "悟");
  16. Student stu = new Student();
  17. BeanUtil.mapValueCopy2Bean(map, stu);
  18. //模拟service处理
  19. stu.setName("悟");
  20. stu.setName(StringUtil.addLikeStringLR(stu.getName()));//两边加 %
  21. //调用mapper(dao)
  22. List<Student> stuList = stuMapper.selectByFormLikeSelective(stu);
  23. //输出验证 预期2行
  24. logger.info("stuList size is: {}", stuList.size());
  25. }
  26. }

JUnit 测试结果:

 

方式2

方式2则是使用 SQL 的 CONCAT 函数,直接在 SQL 中连接 '%' 。

主流数据库都有 CONCAT 函数,另外 Oracle 还可以使用 || 符号更方便,但是为了通用性,建议使用 CONCAT 函数。

修改方式1中的代码。

test 方法中去掉/注掉加百分号行:

  1. //stu.setName(StringUtil.addLikeStringLR(stu.getName()));//两边加 %

xml 中修改目标 like 处为:

  1. <if test="name!=null and name!=''">
  2. <!-- and name like #{name} -->
  3. and name like concat(concat('%', #{name}), '%')
  4. </if>

测试结果(注意dao传入时是没有加百分号的):

 

方式3

方式3使用 mybatis 动态 sql 的 bind 语法,官方地址:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html。

这样的好处是既不要改 service 代码,也不需要使用 CONCAT 函数拼接字段值,只需在 sql 语句块开始处定义属性绑定规则即可。

Mapper.xml 修改:

  1. <select id="selectByFormLikeSelective" parameterType="student" resultMap="BaseResultMap">
  2. <bind name="name" value="'%' + _parameter.getName() + '%'" />
  3. select <include refid="Base_Column_List"/> from student
  4. <where>
  5. <if test="name!=null and name!=''">
  6. and name like #{name}
  7. </if>
  8. <if test="status!=null">
  9. and status = #{status}
  10. </if>
  11. </where>
  12. </select>

运行截图:

 

传入就是带百分号的,可以看出,这种方式其实就是方式1,只不过加 '%' 的事情,mybatis 帮我们做了。

总结

这三种方式都很简单,但是综合而讲,直男君推荐方式1,我们在 service 层自行决定哪个需要模糊查。方式2的话,SQL不简洁;方式3则没有通用性。

表单模糊查询的三种简单方式(springboot-h2-mybatis)的更多相关文章

  1. MyBatis模糊查询的三种拼接方式

    1. sql中字符串拼接 SELECT * FROM tableName WHERE name LIKE CONCAT(CONCAT('%', #{text}), '%'); 2. 使用 ${...} ...

  2. MyBatis 模糊查询的 4 种实现方式

    引言 MyBatis 有 4 种方式可以实现模糊查询. 员工信息表 ( tb_employee ) 如下: id name sex email birthday address 001 张一凡 男 z ...

  3. 2019年6月14日 Web框架之Django_07 进阶操作(MTV与MVC、多对多表三种创建方式、前后端传输数据编码格式contentType、ajax、自定义分页器)

    摘要 MTV与MVC 多对多表三种创建方式 ajax ,前后端传输数据编码格式contentType 批量插入数据和自定义分页器 一.MVC与MTV MVC(Model View Controller ...

  4. ASP.NET Core Razor 编辑表单 - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core Razor 编辑表单 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core Razor 编辑表单 上一章节我们介绍了标签助手和 HT ...

  5. MyBatis实现模糊查询的几种方式

    在学习MyBatis过程中想实现模糊查询,可惜失败了.后来上百度上查了一下,算是解决了.记录一下MyBatis实现模糊查询的几种方式. 数据库表名为test_student,初始化了几条记录,如图: ...

  6. jQuery form插件的使用--用 formData 参数校验表单,验证后提交(简单验证).

    Form Plugin API 里提供了很多有用的方法可以让你轻松的处理表单里的数据和表单的提交过程. 测试环境:部署到Tomcat中的web项目. 一.引入依赖js <script src=& ...

  7. mysql中模糊查询的四种用法介绍

    下面介绍mysql中模糊查询的四种用法: 1,%:表示任意0个或多个字符.可匹配任意类型和长度的字符,有些情况下若是中文,请使用两个百分号(%%)表示. 比如 SELECT * FROM [user] ...

  8. mysql进阶(六)模糊查询的四种用法介绍

    mysql中模糊查询的四种用法介绍 这篇文章主要介绍了mysql中模糊查询的四种用法,需要的朋友可以参考下. 下面介绍mysql中模糊查询的四种用法: 1 %: 表示任意0个或多个字符.可匹配任意类型 ...

  9. Django多对多表的三种创建方式,MTV与MVC概念

    MTV与MVC MTV模型(django): M:模型层(models.py) T:templates V:views MVC模型: M:模型层(models.py) V:视图层(views.py) ...

随机推荐

  1. Codeforces Round #479 (Div. 3) D. Divide by three, multiply by two

    传送门 D. Divide by three, multiply by two •题意 给你一个数 x,有以下两种操作,x 可以任选其中一种操作得到数 y 1.如果x可以被3整除,y=x/3 2.y= ...

  2. php的中文字符

    在使用substr截取字符窜的时候出现乱码的问题 一直任认为字符串是2个字节,直到多次才尝试才总算知道问题所在 php的utf-8字符是每个字符3个字节 而gbk字符是每个字节2个字符 单个字母和符号 ...

  3. docker的基本安装和命令详解

    docker的安装 yum install docker-io docker的启动 /bin/systemctl start docker.service docker查找镜像 docker sear ...

  4. DevOps相关知识点

    DevOps 持续集成 简述 持续集成简称CI,是软件的开发和发布标准流程的最重要的部分 作为一个开发实践,在C中可以通过自动化等手段高频地去获取产品反馈并响应反馈的过程 简单的来说,持续集成就是持续 ...

  5. 关于 '<a[^>]+href=["\'](.*?)["\']' 的解释

    '<a[^>]+href=["\'](.*?)["\']' [] 表示匹配其中的任意字符 ^>  表示除了 > 的字符 ["\'] 表示" ...

  6. go杂货铺

    json序列化 内存中变成可存储或传输的过程称之为序列化(dict,split,struct转string) package main import ( "encoding/json&quo ...

  7. Tomcat 单(多)实例部署使用

    一.前言 (一).概述 Tomcat 是由 Apache 开发的一个 Servlet 容器,实现了对 Servlet 和 JSP 的支持,并提供了作为Web服务器的一些特有功能,如Tomcat管理和控 ...

  8. Android 属性动画实战

    什么是属性动画? 属性动画可以通过直接更改 View 的属性来实现 View 动画.例如: 通过不断的更改 View 的坐标来实现让 View 移动的效果: 通过不断的更改 View 的背景来实现让 ...

  9. Robotframework获取移动端toast问题

    背景: 在做移动端自动化测试的时候,经常会遇到一个问题就是获取toast提示问题,如果需要解决这个问题需要重新处理,不能按照正常的逻辑,使用robotframework自带的关键字进行获取,需要重新考 ...

  10. SpringBoot入门及YML文件详解

    SpringBoot 简介 微框架,与 Spring4 一起诞生,基于约定.生来为了简化 spring 的配置 优点 可以快速的上手,整合了一些子项目(开源框架或者第三方开源库) 可以依赖很少的配置快 ...