SpringDataJpa之动态查询 Example与Specification

本文介绍了SpringDataJpa的动态查询,包括Example查询的 Probe、ExampleMatcher和Example三个部分,适用于带有静态或动态约束的查询。同时,文章探讨了Example的局限性,如不支持嵌套属性等。接着,文章转向Specification,说明其如何扩展JpaSpecificationExecutor,支持更复杂的查询条件,如排序、逻辑运算。最后,提到了在某些复杂场景下,如多表JOIN和返回字段不全时,可能需要使用原生SQL进行操作。
摘要由CSDN通过智能技术生成

动态查询之Example

官方文档介绍

The Query by Example API consists of three parts:

  • Probe: The actual example of a domain object with populated fields.
  • ExampleMatcher: The ExampleMatcher carries details on how to match particular fields. It can be reused across multiple Examples.
  • Example: An Example consists of the probe and the ExampleMatcher. It is used to create the query.

Query by Example is well suited for several use cases:

  • Querying your data store with a set of static or dynamic constraints.
  • Frequent refactoring of the domain objects without worrying about breaking existing queries.
  • Working independently from the underlying data store API.

Query by Example also has several limitations:

  • No support for nested or grouped property constraints, such as firstname = ?0 or (firstname = ?1 and lastname = ?2).
  • Only supports starts/contains/ends/regex matching for strings and exact matching for other property types.
    example中文介绍

使用

        UUser user = new UUser();
		user.setUserName("e");
		user.setStatus(1);
		ExampleMatcher matcher = ExampleMatcher.matching()
				.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())//模糊查询匹配开头,即{userNamee}%
				;
		Example<UUser> userExample = Example.of(user, matcher);
		userRepository.findAll(userExample);

上述设置将模糊匹配 userName包含‘e’,且status等于1 的全部对象
上例中设置匹配器规则,也可使用默认的匹配器规则,默认是属性不为空的就根据属性值进行查询

匹配器规则

Matching 生成的语句 说明
DEFAULT (case-sensitive) firstname = ?0 默认(大小写敏感)
DEFAULT (case-insensitive) LOWER(fir
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值