springdata jpa使用Example快速实现动态查询功能

目录
  • Example官方介绍
  • Example api的组成
  • 限制
  • 使用
    • 测试查询
    • 自定匹配器规则
  • 补充
    • 官方创建ExampleMatcher例子(1.8 lambda)
    • StringMatcher 参数
  • 总结

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下测试报错,不了解具体作用。

总结

通过在使用springdata jpa时可以通过Example来快速的实现动态查询,同时配合Pageable可以实现快速的分页查询功能。

对于非字符串属性的只能精确匹配,比如想查询在某个时间段内注册的用户信息,就不能通过Example来查询

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring Data JPA实现动态查询的两种方法

    前言 一般在写业务接口的过程中,很有可能需要实现可以动态组合各种查询条件的接口.如果我们根据一种查询条件组合一个方法的做法来写,那么将会有大量方法存在,繁琐,维护起来相当困难.想要实现动态查询,其实就是要实现拼接SQL语句.无论实现如何复杂,基本都是包括select的字段,from或者join的表,where或者having的条件.在Spring Data JPA有两种方法可以实现查询条件的动态查询,两种方法都用到了Criteria API. Criteria API 这套API可用于构建对数据

  • 详解Spring Data JPA动态条件查询的写法

    我们在使用SpringData JPA框架时,进行条件查询,如果是固定条件的查询,我们可以使用符合框架规则的自定义方法以及@Query注解实现. 如果是查询条件是动态的,框架也提供了查询接口. JpaSpecificationExecutor 和其他接口使用方式一样,只需要在你的Dao接口继承即可(官网代码). public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecification

  • Spring Data JPA实现动态条件与范围查询实例代码

    Spring Data JPA为我们提供了Query With Example来实现动态条件查询,当查询条件为空的时候,我们不用做大量的条件判断.但是Query With Example却不支持范围查询(包括日期范围,数值范围查询),本文通过Specification实现了既支持动态条件查询又支持范围查询的方法. 1 实现方式 1.1 范围对象Range定义 import java.io.Serializable; public class Range<E> implements Serial

  • Spring Data JPA中的动态查询实例

    spring Data JPA大大的简化了我们持久层的开发,但是实际应用中,我们还是需要动态查询的. 比如,前端有多个条件,这些条件很多都是可选的,那么后端的SQL,就应该是可以定制的,在使用hibernate的时候,可以通过判断条件来拼接SQL(HQL),当然,Spring Data JPA在简化我们开发的同时,也是提供了支持的. 通过实现Criteria二实现的动态查询,需要我们的Repo接口继承JpaSpecificationExecutor接口,这是个泛型接口. 然后查询的时候,传入动态

  • springdata jpa使用Example快速实现动态查询功能

    目录 Example官方介绍 Example api的组成 限制 使用 测试查询 自定匹配器规则 补充 官方创建ExampleMatcher例子(1.8 lambda) StringMatcher 参数 总结 Example官方介绍 Query by Example (QBE) is a user-friendly querying technique with a simple interface. It allows dynamic query creation and does not r

  • XML卷之实战锦囊(2):动态查询

    动机: 查询功能是我们在网站上见过的最普遍也是最常用的一个功能模块了.以往的信息查询都是连接到数据库的,每一次点击都必须要后台数据库的支持.然而很多情况下用户往往只针对某一部分的数据进行操作,这样不但服务器的负担加重,而且严重的影响用户浏览的速度. 针对这种情况我们需要将用户需要的某一部分数据以XML的方式传递到客户端,用户对这些数据可以很方便的进行操作.既方便了用户,又减轻了服务器数据库的负担.何乐而不为呢!而且这项功能可以通用到其他众多模块,因此添加了这个动态查询功能. 材料: XML卷之动

  • SpringData JPA实现查询分页demo

    SpringData JPA 的 PagingAndSortingRepository接口已经提供了对分页的支持,查询的时候我们只需要传入一个 org.springframework.data.domain.Pageable 接口的实现类,指定PageNumber和pageSize即可 springData包中的 PageRequest类已经实现了Pageable接口,我们可以直接使用下边是部分代码: DAO: package com.jiaoyiping.jdjy.sourcecode.dao

  • JPA多条件复杂SQL动态分页查询功能

    概述 ORM映射为我们带来便利的同时,也失去了较大灵活性,如果SQL较复杂,要进行动态查询,那必定是一件头疼的事情(也可能是lz还没发现好的方法),记录下自己用的三种复杂查询方式. 环境 springBoot IDEA2017.3.4 JDK8 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0&q

  • Spring data jpa的使用与详解(复杂动态查询及分页,排序)

    一. 使用Specification实现复杂查询 (1) 什么是Specification Specification是springDateJpa中的一个接口,他是用于当jpa的一些基本CRUD操作的扩展,可以把他理解成一个spring jpa的复杂查询接口.其次我们需要了解Criteria 查询,这是是一种类型安全和更面向对象的查询.而Spring Data JPA支持JPA2.0的Criteria查询,相应的接口是JpaSpecificationExecutor. 而JpaSpecifica

  • 使用JPA+querydsl如何实现多条件动态查询

    目录 JPAquerydsl多条件动态查询 介绍一下querydsl 看源码 springdataJPA和querydsl 什么是SpringDataJPA?什么是QueryDSL? @Mapper实体-模型映射 项目整体流程 疑问 JpaRepository SimpleJpaRepository 写一个Repository继承JpaRepository之后 spring-data-jpa的相关语法 JPA querydsl多条件动态查询 相信很多人在做订单管理的时候会用到多条件的检索,比如说

  • SpringData JPA基本/高级/多数据源的使用详解

    目录 一.SpringDataJPA基本用法 1.概念 JPA由来 JPA是什么 SpringDataJPA 2.快速上手 1.添加依赖 2.添加配置文件 3.实体类 4.Repository构建 5.测试 6.基本查询 7.自定义查询 3.小结 二.SpringDataJPA高级用法 1.自定义SQL查询 2.分页查询SpringDataJPA已经帮我们内置了分页功能 3.复杂查询 4.多表查询 5.小结 三.SpringDataJPA多数据源使用 1.前言 2.多数据源的支持 3.小结 一.

  • springdata jpa单表操作crud的实例代码详解

    1. 项目搭建 使用boot整合,导入springdata jap, mysql 驱动,lombok,web. 1.1 配置 # boot add jpa, oh~ crud in single table server: port: 8888 spring: # datasource datasource: username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://

随机推荐