springdata jpa使用Example快速实现动态查询功能
作者:一号搬砖手 发布时间:2022-12-01 21:49:08
Example官方介绍
Query by Example (QBE) is a user-friendly querying technique with a simple interface. It allows dynamic query creation and does not require to write queries containing field names. In fact, Query by Example does not require to write queries using store-specific query languages at all.
谷歌翻译:
按例查询(QBE)是一种用户界面友好的查询技术。 它允许动态创建查询,并且不需要编写包含字段名称的查询。 实际上,按示例查询不需要使用特定的数据库的查询语言来编写查询语句。
Example api的组成
Probe
:含有对应字段的实例对象。ExampleMatcher
:ExampleMatcher携带有关如何匹配特定字段的详细信息,相当于匹配条件。Example
:由Probe和ExampleMatcher组成,用于查询。
限制
属性不支持嵌套或者分组约束,比如这样的查询 firstname = ?0 or (firstname = ?1 and lastname = ?2)
灵活匹配只支持字符串类型,其他类型只支持精确匹配
Limitations
1. No support for nested/grouped property constraints like firstname = ?0 or (firstname = ?1 and lastname = ?2)
2. Only supports starts/contains/ends/regex matching for strings and exact matching for other property types
使用
创建实体映射:
@Entity
@Table(name="t_user")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
@Column(name="email")
private String email;
@Column(name="phone")
private String phone;
@Column(name="address")
private String address;
}
测试查询
@Test
public void contextLoads() {
User user = new User();
user.setUsername("admin");
Example<User> example = Example.of(user);
List<User> list = userRepository.findAll(example);
System.out.println(list);
}
打印的sql语句如下:
Hibernate:
select
user0_.id as id1_0_,
user0_.address as address2_0_,
user0_.email as email3_0_,
user0_.password as password4_0_,
user0_.phone as phone5_0_,
user0_.username as username6_0_
from
t_user user0_
where
user0_.username=?
可以发现,试用Example查询,默认情况下会忽略空值,官方文档也有说明:
This is a simple domain object. You can use it to create an Example. By default, fields having null values are ignored, and strings are matched using the store specific defaults. Examples can be built by either using the of factory method or by using ExampleMatcher. Example is immutable.
在上面的测试之中,我们只是只是定义了Probe而没有ExampleMatcher,是因为默认会不传时会使用默认的匹配器。点进方法可以看到下面的代码:
static <T> Example<T> of(T probe) {
return new TypedExample(probe, ExampleMatcher.matching());
}
static ExampleMatcher matching() {
return matchingAll();
}
static ExampleMatcher matchingAll() {
return (new TypedExampleMatcher()).withMode(ExampleMatcher.MatchMode.ALL);
}
自定匹配器规则
@Test
public void contextLoads() {
User user = new User();
user.setUsername("y");
user.setAddress("sh");
user.setPassword("admin");
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.startsWith())//模糊查询匹配开头,即{username}%
.withMatcher("address" ,ExampleMatcher.GenericPropertyMatchers.contains())//全部模糊查询,即%{address}%
.withIgnorePaths("password");//忽略字段,即不管password是什么值都不加入查询条件
Example<User> example = Example.of(user ,matcher);
List<User> list = userRepository.findAll(example);
System.out.println(list);
}
打印的sql语句如下:
select
user0_.id as id1_0_,
user0_.address as address2_0_,
user0_.email as email3_0_,
user0_.password as password4_0_,
user0_.phone as phone5_0_,
user0_.username as username6_0_
from
t_user user0_
where
(
user0_.username like ?
)
and (
user0_.address like ?
)
参数如下:
2018-03-24 13:26:57.425 TRACE 5880 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [y%]
2018-03-24 13:26:57.425 TRACE 5880 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [%sh%]
补充
官方创建ExampleMatcher例子(1.8 lambda)
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("firstname", match -> match.endsWith())
.withMatcher("firstname", match -> match.startsWith());
}
StringMatcher 参数
Matching | 生成的语句 | 说明 |
---|---|---|
DEFAULT (case-sensitive) | firstname = ?0 | 默认(大小写敏感) |
DEFAULT (case-insensitive) | LOWER(firstname) = LOWER(?0) | 默认(忽略大小写) |
EXACT (case-sensitive) | firstname = ?0 | 精确匹配(大小写敏感) |
EXACT (case-insensitive) | LOWER(firstname) = LOWER(?0) | 精确匹配(忽略大小写) |
STARTING (case-sensitive) | firstname like ?0 + ‘%' | 前缀匹配(大小写敏感) |
STARTING (case-insensitive) | LOWER(firstname) like LOWER(?0) + ‘%' | 前缀匹配(忽略大小写) |
ENDING (case-sensitive) | firstname like ‘%' + ?0 | 后缀匹配(大小写敏感) |
ENDING (case-insensitive) | LOWER(firstname) like ‘%' + LOWER(?0) | 后缀匹配(忽略大小写) |
CONTAINING (case-sensitive) | firstname like ‘%' + ?0 + ‘%' | 模糊查询(大小写敏感) |
CONTAINING (case-insensitive) | LOWER(firstname) like ‘%' + LOWER(?0) + ‘%' | 模糊查询(忽略大小写) |
说明:
1. 在默认情况下(没有调用withIgnoreCase())都是大小写敏感的。
2. api之中还有个regex,但是我在mysql下测试报错,不了解具体作用。
来源:https://blog.csdn.net/long476964/article/details/79677526


猜你喜欢
- 问题: 在win10系统中,使用IDEA 查看源码的时候,经常跳转代码,这样会让使用者感觉和方便,但是当你想要返回上次跳转的位置时,却不知道
- 引言 在c#中,可能大多数人针对于多线程之间的通讯,是熟能生巧,对于AsyncLocal 和Thre
- 本文实例讲述了Android MediaPlayer基本使用方法。分享给大家供大家参考,具体如下:使用MediaPlayer播放音频或者视频
- 1. 新建TestServlet类package com.yanek.test;import java.io.IOException;imp
- 本文记录了笔者的第一个Java程序,基于Java抽象窗口工具(abstract window toolkit , AWT)和Swing(Sw
- 悲观锁、乐观锁简介: 悲观锁:同步操作。即用户A在操作某条数据时,为其上锁,限制其他用户操作,用户A操作完成提交事务后其他用户方可
- 前言最近接手了一个老项目,“愉悦的心情”自然无以言表,做开发的朋友都懂,这里就不多说了,都是泪...
- 登陆的时候,发现输入账号的不同大小写竟然能够登陆。Mybatis查询代码如下<select id="selectById&q
- 本文实例讲述了Java使用备忘录模式实现过关类游戏功能。分享给大家供大家参考,具体如下:一.模式定义备忘录模式,在不破坏封闭的前提下,捕获一
- 一、XML DOM概述XML 文档大小写敏感、属性用引号括起来,每一个标记都要闭合。DOM是XML文档的内存中树状的表示形式。继承关系图:X
- java解析json数组最简单的json数组[ { &quo
- 文件作为存储数据的单元,会根据数据类型产生很多分类,也就是所谓的文件类型。在对数据文件进行操作时,常常需要根据不同的文件类型来作不同的处理。
- mport java.text.DecimalFormat; DecimalFormat &nb
- 导出Excel的框架有很多种,POI相对来说比较老了,很多Excel框架底层都是POI、有EasyPoi、EasyExcel、包括Hutoo
- java7增强的try语句关闭资源传统的关闭资源方式import java.io.FileInputStream;import java.i
- DataSet 对象是支持 ADO.NET的断开式、分布式数据方案的核心对象 ,用途非常广泛.我们很多时候需要使用其中的数据,比如取得一个D
- Java的List在删除元素时,一般会用list.remove(o)/remove(i)方法。在使用时,容易触碰陷阱,得到意想不到的结果。总
- 好久没有写过博客了,最近因项目需求,需要用到Socket来进行通信,简单写了几个例子,记录一下,代码很简单,无非就是接收与发送,以及接收到数
- 1、@Valid与@Validated的区别1.1 基本区别@Valid:Hibernate validation校验机制@Validate
- 方法的递归调用1. 基本介绍:简单地说,递归就是方法自己调用自己,每次调用时传入不同的变量,递归有助于编程者解决复杂问题的同时让代码变得简洁