如何在 JPA @Query 注释中使用 IN 子句

How to use the IN clause in an JPA @Query annotation

我已经定义了这个方法

 @Query("select cs from CenterStudy cs where cs.id in (?1)")
 @EntityGraph(value = "centerStudyAndNotifiedUsers", type = EntityGraph.EntityGraphType.LOAD)
 List<CenterStudy> findAllByIdsWithCenterAndUsers(List<Long> ids);

带有 id 的列表不为空,也不为空,但我总是得到以下异常:

java.lang.NullPointerException
    at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
    at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:613)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)

我很确定这与 IN 子句的定义方式有关。

欢迎提出任何建议!

public List<DealInfo> getDealInfos(List<String> dealIds) {
        String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
        TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
        query.setParameter("inclList", dealIds);
        return query.getResultList();
    }

适用于 JPA 2

这是一个常见问题,是 Hibernate 中的一个错误,您可以在 :

找到

NullPointer when combining JPQL query with in clause and @NamedEntityGraph 上面写着:

When you combine a JPQL query with an in clause and a @NamedEntityGraph you get a NullPointerException in org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67) when you execute the query.

因此您必须删除此处的 @EntityGraph 注释才能解决此问题。

我以前遇到过这个问题。我使用命名参数而不是位置参数修复了它。 示例:

"Select p from product where p.id in(?)" -- not working

替换为:

"Select p from product where p.id in(:idList)" -- OK