首页 > 解决方案 > Spring命名+jpa方法

问题描述

我有一个简单的 JpaRespository,我必须在其中使用一些带有弹簧命名的方法

它看起来像 sql

select * from a where a.user_id in ( some id values)

在 jpa 中,相同的查询将如下所示

List<A> findAllByUserIdIn(List<Long>ids) 

它的工作非常好

我需要知道什么?如何在 spring 命名方法中创建相同的查询

在 sql 它看起来像

select * from a where a.user_id in ( some values...) and ( a.created_at <='some date" or a.updated_at<='some date)

我试图做这样的事情

List<A> findAllByUserIdInAndCreatedAtLessThanEqualOrUpdatedAtLessThanEqual(List<Long>ids,TimeStamp created_at,TimeStamp  updated_at)

但它不能正常工作 - 它给我的所有记录的更新少于这个日期,但它们不在当前的 user_ids 列表中,我知道为什么 - 因为如果我做 AndUpdatedAtLessThanEqual 它的 OrUpdatedAtLessThanEqual 它也不能正常工作

那么有什么方法可以在不创建本机查询的情况下做我需要的事情

标签: jpa

解决方案


您所写findAllByUserIdInAndCreatedAtLessThanEqualOrUpdatedAtLessThanEqual的内容是正确的,但如果您仔细查看本机查询,您会发现括号将条件分组。

Requirement - condition1 AND (condition2 OR condition3)
Your method name - condition1 AND condition2 OR condition3

由于没有适应分组条件的功能,因此您将不得不使用@Query注释。

@Query 注解不仅减少了长 JPA 方法名不可读的问题,而且消除了连接的使用(因为您将使用 Entity 中使用的参数名而不是表中的列名),这反过来又提高了可读性并减少了使用本机查询。


推荐阅读