You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data JPA能否通过查询方法名实现逻辑运算符分组?

解决方案

不需要使用JPQL和@Query注解,有两种方式可以实现你的查询需求:

方案一:利用逻辑等价性编写派生查询方法

由于groupID = ? AND (name LIKE %?% OR description LIKE %?%)与(groupID = ? AND name LIKE %?%) OR (groupID = ? AND description LIKE %?%)逻辑完全等价,你可以编写如下派生查询方法:

public interface ThingRepo extends JpaRepository<Thing, Long> {
    Collection<Thing> findByGroupIDAndNameContainsOrGroupIDAndDescriptionContains(Long groupID, String keyword, Long groupID2, String keyword2);
}

调用时只需给重复参数传入相同的值即可:

// 查询groupID为1,name或description包含"test"的记录
Collection<Thing> things = thingRepo.findByGroupIDAndNameContainsOrGroupIDAndDescriptionContains(1L, "test", 1L, "test");

方案二:使用Query by Example(QBE)查询

Spring Data JPA的Example查询支持通过配置匹配规则实现OR逻辑,步骤如下:

  1. 让仓库接口继承QueryByExampleExecutor<Thing>:
public interface ThingRepo extends JpaRepository<Thing, Long>, QueryByExampleExecutor<Thing> {
}
  1. 构建Example查询并执行:
// 配置匹配规则:name和description采用包含匹配,且两个条件为OR关系
ExampleMatcher matcher = ExampleMatcher.matching()
        .withMatcher("name", match -> match.contains())
        .withMatcher("description", match -> match.contains())
        .withIgnorePaths("groupID") // 跳过groupID的默认匹配规则
        .withAnyMatch(); // 多个属性的匹配条件用OR连接

// 创建查询探针,设置groupID的查询条件
Thing probe = new Thing();
probe.setGroupID(1L);

// 执行查询
Collection<Thing> things = thingRepo.findAll(Example.of(probe, matcher));

内容的提问来源于stack exchange,提问作者E-Riz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:27:53