表单模糊查询的三种简单方式(springboot-h2-mybatis)
前几天运营提到说后台管理系统有几个地方想要模糊查询..
想了下是简单的,就是要注意以前方法的被调用情况,进行增量改动,以免牵一发而动全身。整理一波记录下(本次案例是按名字模糊查询学生信息)。
三种方式概览
- SQL 语句正常 like,service 层按需要添加 '%'
- SQL 使用 CONCAT 函数
- mybatis 的 bind 语法
依旧使用H2数据库(>>springboot与H2数据库快速本地测试),初始化脚本配置一个简单的学生表,添几条记录。
H2和mybatis相关配置
1)maven依赖
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
2)application.properties
server.port=8091
server.servlet.context-path=/tsa
#spring.datasource.url=jdbc:h2:mem:test
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=123456
spring.datasource.schema=classpath:h2sql/schema.sql
spring.datasource.data=classpath:h2sql/data.sql
spring.h2.console.enabled=true
#localhost:8080/projectName/h2-console
spring.h2.console.path=/h2-console
#mybatis.config-location=classpath:/mybatis-config.xml
mybatis.mapper-locations=classpath:/sqlmap/*Mapper.xml
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.hwc.tsa.bean
logging.level.com.hwc.tsa.dao=debug
logging.level.com.hwc.tsa.mapper=debug
3)H2初始化脚本(学生表)
h2sql/schema.sql
drop table if exists student;
create table student(
id int unsigned not null auto_increment comment '自增主键',
name varchar(20) not null comment '字典类型-关联字段',
age int unsigned not null comment '年龄', status tinyint not null default 1 comment '逻辑删除字段',
crt_time timestamp not null default CURRENT_TIMESTAMP comment '创建时间',
upd_time timestamp default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP comment '更新时间', PRIMARY KEY (id)
);
h2sql/data.sql
insert into student(name, age) values ('菠萝包', 1);
insert into student(name, age) values ('皮卡丘', 3);
insert into student(name, age) values ('悟空', 35);
insert into student(name, age) values ('悟饭', 21);
insert into student(name, age) values ('克林', 37);
insert into student(name, age) values ('弗利沙', 999);
insert into student(name, age) values ('妙蛙种子', 3);
insert into student(name, age) values ('杰尼龟', 2);
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 新增方法(按名字模糊查):
/**
* 表单模糊查询支持
* @param record
* @return
*/
List<Student> selectByFormLikeSelective(Student record);
StudentMapper.xml 新增查询映射点:
<select id="selectByFormLikeSelective" parameterType="student" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/> from student
<where>
<if test="name!=null and name!=''">
and name like #{name}
</if>
<if test="status!=null">
and status = #{status}
</if>
</where>
</select>
编写测试类:
@RunWith(SpringRunner.class)
//不加载web环境,更快捷测试
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
//@SpringBootTest
public class MapperDaoTests {
private static final Logger logger = LoggerFactory.getLogger(MapperDaoTests.class); @Autowired
StudentMapper stuMapper; @Test
public void testStudentMapperLikeSelective() {
//模拟controller输入
Map<String, Object> map = new HashMap<>();
map.put("name", "悟");
Student stu = new Student();
BeanUtil.mapValueCopy2Bean(map, stu);
//模拟service处理
stu.setName("悟");
stu.setName(StringUtil.addLikeStringLR(stu.getName()));//两边加 %
//调用mapper(dao)
List<Student> stuList = stuMapper.selectByFormLikeSelective(stu);
//输出验证 预期2行
logger.info("stuList size is: {}", stuList.size());
}
}
JUnit 测试结果:
方式2
方式2则是使用 SQL 的 CONCAT 函数,直接在 SQL 中连接 '%' 。
主流数据库都有 CONCAT 函数,另外 Oracle 还可以使用 || 符号更方便,但是为了通用性,建议使用 CONCAT 函数。
修改方式1中的代码。
test 方法中去掉/注掉加百分号行:
//stu.setName(StringUtil.addLikeStringLR(stu.getName()));//两边加 %
xml 中修改目标 like 处为:
<if test="name!=null and name!=''">
<!-- and name like #{name} -->
and name like concat(concat('%', #{name}), '%')
</if>
测试结果(注意dao传入时是没有加百分号的):
方式3
方式3使用 mybatis 动态 sql 的 bind 语法,官方地址:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html。
这样的好处是既不要改 service 代码,也不需要使用 CONCAT 函数拼接字段值,只需在 sql 语句块开始处定义属性绑定规则即可。
Mapper.xml 修改:
<select id="selectByFormLikeSelective" parameterType="student" resultMap="BaseResultMap">
<bind name="name" value="'%' + _parameter.getName() + '%'" />
select <include refid="Base_Column_List"/> from student
<where>
<if test="name!=null and name!=''">
and name like #{name}
</if>
<if test="status!=null">
and status = #{status}
</if>
</where>
</select>
运行截图:
传入就是带百分号的,可以看出,这种方式其实就是方式1,只不过加 '%' 的事情,mybatis 帮我们做了。
总结
这三种方式都很简单,但是综合而讲,直男君推荐方式1,我们在 service 层自行决定哪个需要模糊查。方式2的话,SQL不简洁;方式3则没有通用性。
表单模糊查询的三种简单方式(springboot-h2-mybatis)的更多相关文章
- MyBatis模糊查询的三种拼接方式
1. sql中字符串拼接 SELECT * FROM tableName WHERE name LIKE CONCAT(CONCAT('%', #{text}), '%'); 2. 使用 ${...} ...
- MyBatis 模糊查询的 4 种实现方式
引言 MyBatis 有 4 种方式可以实现模糊查询. 员工信息表 ( tb_employee ) 如下: id name sex email birthday address 001 张一凡 男 z ...
- 2019年6月14日 Web框架之Django_07 进阶操作(MTV与MVC、多对多表三种创建方式、前后端传输数据编码格式contentType、ajax、自定义分页器)
摘要 MTV与MVC 多对多表三种创建方式 ajax ,前后端传输数据编码格式contentType 批量插入数据和自定义分页器 一.MVC与MTV MVC(Model View Controller ...
- ASP.NET Core Razor 编辑表单 - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core Razor 编辑表单 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core Razor 编辑表单 上一章节我们介绍了标签助手和 HT ...
- MyBatis实现模糊查询的几种方式
在学习MyBatis过程中想实现模糊查询,可惜失败了.后来上百度上查了一下,算是解决了.记录一下MyBatis实现模糊查询的几种方式. 数据库表名为test_student,初始化了几条记录,如图: ...
- jQuery form插件的使用--用 formData 参数校验表单,验证后提交(简单验证).
Form Plugin API 里提供了很多有用的方法可以让你轻松的处理表单里的数据和表单的提交过程. 测试环境:部署到Tomcat中的web项目. 一.引入依赖js <script src=& ...
- mysql中模糊查询的四种用法介绍
下面介绍mysql中模糊查询的四种用法: 1,%:表示任意0个或多个字符.可匹配任意类型和长度的字符,有些情况下若是中文,请使用两个百分号(%%)表示. 比如 SELECT * FROM [user] ...
- mysql进阶(六)模糊查询的四种用法介绍
mysql中模糊查询的四种用法介绍 这篇文章主要介绍了mysql中模糊查询的四种用法,需要的朋友可以参考下. 下面介绍mysql中模糊查询的四种用法: 1 %: 表示任意0个或多个字符.可匹配任意类型 ...
- Django多对多表的三种创建方式,MTV与MVC概念
MTV与MVC MTV模型(django): M:模型层(models.py) T:templates V:views MVC模型: M:模型层(models.py) V:视图层(views.py) ...
随机推荐
- 使用.csv文件
引用自:https://blog.csdn.net/vision_tung/article/details/79845758 通用爬虫:https://blog.csdn.net/Vision_Tun ...
- GGPLOT2-plotly |让你的火山图“活”过来
火山图(Volcano Plot)常用于展示基因表达差异的分布,横坐标常为Fold change(倍数),越偏离中心差异倍数越大;纵坐标为P值(P值),值越大差异越显着.原因得名也许的英文因为查询查询 ...
- Wireshark着色规则
wireshark抓包蓝色和红色 在默认情况下 蓝色适合红色相反的方向 绿色背景的是HTTP包灰色背景的是TCP包.黑色背景的是TCP错误包或者校验和错误的包 有时候wireshark抓的包还有颜色区 ...
- Linux常用的命令及使用方法
1.请用命令查出ifconfig命令程序的绝对路径 [root@localhost ~]# which ifconfig(ifconfig是linux中用于显示或配置网络设备(网络接口卡)的命令) / ...
- DesignPattern系列__03依赖倒置原则
依赖倒置原则(Dependence Inversion Priiciple,DIP) 介绍 High level modules should not depend upon low level mo ...
- Qt基于sqlite数据库的管理小软件
闲来无事,写了一个基于sqlite的数据库管理小软件. 先上图 中心思想就是: 创建一个数据库 然后每一个分组对应一个数据表 然后遍历该数据表.将名字以treewidgetItem显示出来.添加删除实 ...
- 高性能MySQL之事物
一.概念 事务到底是什么东西呢?想必大家学习的时候也是对事务的概念很模糊的.接下来通过一个经典例子讲解事务. 银行在两个账户之间转账,从A账户转入B账户1000元,系统先减少A账户的1000元,然后再 ...
- 如何使用dmidecode命令查看硬件信息
引言 当我们需要获取机器硬件信息时,可使用linux系统自带的dmidecode工具进行查询. dmidecode命令通过读取系统DMI表,显示服务器硬件和BIOS信息.除了可使用dmidecode查 ...
- Maven 项目使用mybatis的环境搭建-基于xml形式实现查询所有的功能
首先了解一下什么是 MyBatis? MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集. ...
- API开发之接口安全(三)----sign有效时间
之前生成的sign和校验sign我们已经完全掌握了.但是仅仅凭借这样的sign是无法满足我们的需求的,如果一个黑客通过抓包抓到你的数据 他可以去修改你的header为这样的 body为那样的 也是可以 ...