如何使用“IN”创建自定义 Spring JPA 查询?

Posted

技术标签:

【中文标题】如何使用“IN”创建自定义 Spring JPA 查询?【英文标题】:How do you create a custom Spring JPA query using "IN"? 【发布时间】:2019-09-25 15:57:12 【问题描述】:

我有一个整数参数。我需要编写一个自定义 Spring JPA 查询,其中等效 SQL 将是。 . . AND x.propertyStatusId IN (1,2) 。 . .

我在 Spring Data JPA 文档中看到关键字是“IN”,就像在 "findByAgeIn(Collection<Age> ages)" 中一样,它转换为“where x.age in ?1”但我收到一个错误。我正在使用整数的arrayList。

ArrayList<Integer> propertyStatusId = new ArrayList<Integer>();
propertyStatusId.add(1);
propertyStatusId.add(2);
findByPropertyOwnerIdAndIn(propertyStatusId)AndListingDateGreaterThanEqual(user.getId(),propertyStatusId, ListingDate, pageable);

【问题讨论】:

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause的可能重复 【参考方案1】:

假设您有一个名为Product 的实体,定义如下:

@Entity
public class Product 

    @Id
    @GeneratedValue
    private Integer id;
    private String title;
    private String description;
    private Date createDate;

// getters & setters 



如果您需要基于titleList of idsgreater than or equal to createDate 进行查询,则可以定义如下方法:

List<Product> findByTitleAndIdInAndCreateDateGreaterThanEqual(String title, List<Integer> ids, Date createDate);

【讨论】:

是的,这个编译并帮助我克服了围绕这个特定部分的构建的编译错误。我仍然遇到关于它由于某种原因无法识别属性名称的错误问题。但我会像以前那样解决这个问题(我知道这是实体名称而不是 SQL 名称等)。谢谢 我很高兴听到这个消息。谢谢@STP!

以上是关于如何使用“IN”创建自定义 Spring JPA 查询?的主要内容,如果未能解决你的问题,请参考以下文章

使用 Spring DATA JPA 创建自定义查询?

使用 spring-data-jpa 自定义 ItemReader

如何在 JPA 中生成自定义 ID

在为嵌套对象创建自定义 Spring Data JPA 查询时获取 IllegalArgumentException

如何从 Spring Data JPA GROUP BY 查询中返回自定义对象

在 JPA 存储库(Spring Data Jpa)中执行自定义查询