带有IN子句的Spring Data JPA中的NPE

时间:2015-01-26 13:23:03

标签: java spring hibernate jpa spring-data-jpa

我使用Spring Data JPA 1.7.1和Hibernate 4.3.7作为我的JPA提供程序。我有以下Spring Data JPA存储库:

@Repository
public interface CompanyRepository extends JpaRepository<Company, Integer> {
    @EntityGraph(value = "graph.company.search.results", type = EntityGraph.EntityGraphType.FETCH)
    @Query("SELECT c FROM Company c WHERE c.id IN :companyIds")
    List<Company> findByCompanyIdsForSearchResults(@Param("companyIds") Set<Integer> companyIds);
}

以下代码调用上述存储库方法:

Set<Integer> companyIds = new HashSet<>();
companyIds.add(100000);
// companyIds.add(100001); // This line breaks the code
List<Company> companies = this.companyRepository.findByCompanyIdsForSearchResults(companyIds);

我遇到上述奇怪的行为。首先,如果我只在集合中放入一个ID,那么在我的列表中会返回两个 Company个实例,即使ID显然是唯一的。其次,如果我向集合中添加了多个ID,则代码将失败并显示以下NullPointerException

java.lang.NullPointerException
    org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
    org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:616)
    org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1901)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1839)
    org.hibernate.loader.Loader.doQuery(Loader.java:910)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
    org.hibernate.loader.Loader.doList(Loader.java:2554)
    org.hibernate.loader.Loader.doList(Loader.java:2540)
    org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
    org.hibernate.loader.Loader.list(Loader.java:2365)
    org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
    org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236)
    org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
    org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
    org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:449)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:362)
    com.sun.proxy.$Proxy217.getResultList(Unknown Source)
    org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:110)
    org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
    org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:98)
    org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:89)
    org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:421)
    org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:381)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:512)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    com.sun.proxy.$Proxy177.findByCompanyIdsForSearchResults(Unknown Source)

    ...

我还尝试将Set更改为List,但结果相同。生成的查询的WHERE子句如下所示:where company0_.id in (?)

我做错了什么,或者这是一个错误?我使用@Query而不是命名方法findByIdIn的原因是我希望自由根据上下文为我的方法命名一些独特的东西(因为实体图取决于方法的上下文被调用)。我想要做的甚至支持吗?

提前谢谢。

编辑#3:事实证明,由于@EntityGraph注释而引发了异常。这很奇怪,因为我使用了具有@Query注释的其他存储库方法的实体图,并且一切正常。但是,似乎@EntityGraphIN子句的组合会导致问题。这似乎是一个错误。如果我删除IN子句并将方法更改为查找单个公司,则一切都可以与实体图一起使用。有没有人对解决方案或解决方法有任何想法?我可以&#34;手动&#34; JOIN FETCH我的关联,但这并不像使用实体图那样漂亮。

编辑#2:有趣的是,如果我编写自定义存储库方法as described here,一切都会按预期工作。以下代码工作正常:

public List<Company> test(Set<Integer> companyIds) {
    String jpql = "select c from Company c where c.id in :companyIds";
    Query q = this.getEntityManager().createQuery(jpql);
    q.setParameter("companyIds", companyIds);
    List results = q.getResultList(); // Contains X entities, and works with > 1 company IDs as well

    return null;
}

显然这个问题与Spring Data JPA自动实现我的接口方法有关。我可以只使用&#34; custom&#34;实现,但如果我可以使用第一种方法会更好,所以我仍然在寻找原始问题的解决方案。

编辑#1:以下是Company实体的源代码(不包括getter和setter)。

@Entity
@Table(name = "company", uniqueConstraints = {
        @UniqueConstraint(columnNames = { "slug" })
})
@NamedEntityGraphs({
        @NamedEntityGraph(
                name = "graph.company.profile.view",
                attributeNodes = {
                        @NamedAttributeNode(value = "city"),
                        @NamedAttributeNode(value = "acknowledgements"),
                        @NamedAttributeNode(value = "industries"),
                        @NamedAttributeNode(value = "companyServices", subgraph = "companyServices")
                },
                subgraphs = {
                        @NamedSubgraph(name = "companyServices", attributeNodes = {
                                @NamedAttributeNode(value = "service")
                        })
                }
        ),

        @NamedEntityGraph(
        name = "graph.company.search.results",
        attributeNodes = {
                @NamedAttributeNode(value = "city"),
                @NamedAttributeNode(value = "acknowledgements"),
                @NamedAttributeNode(value = "industries"),
                @NamedAttributeNode(value = "companyServices", subgraph = "companyServices")
        },
        subgraphs = {
                @NamedSubgraph(name = "companyServices", attributeNodes = {
                        @NamedAttributeNode(value = "service")
                })
        }
)
})
public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private int id;

    @NotEmpty
    @Length(min = 5, max = 100)
    @Column(length = 100, nullable = false)
    private String name;

    @Length(min = 3, max = 50)
    @Column(length = 50)
    private String slug;

    @Column
    private Double rating;

    @Column(name = "number_of_reviews")
    private int numberOfReviews;

    @Length(min = 5, max = 50)
    @Column(name = "street_name", length = 50)
    private String streetName;

    @Length(max = 25)
    @Column(name = "street_number", length = 25)
    private String streetNumber;

    @Length(min = 8, max = 11)
    @Column(name = "phone_number", length = 11)
    private String phoneNumber;

    @Length(min = 8, max = 11)
    @Column(name = "second_phone_number", length = 11)
    private String secondPhoneNumber;

    @Length(min = 50, max = 175)
    @Column
    private String teaser;

    @Length(min = 50, max = 5000)
    @Column
    private String description;

    @Length(min = 8, max = 8)
    @Column(name = "ci_number", nullable = false)
    private long ciNumber;

    @ManyToOne(fetch = FetchType.EAGER, targetEntity = City.class, optional = false)
    @JoinColumn(name = "postal_code")
    private City city;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "company_acknowledgement", joinColumns = @JoinColumn(name = "company_id"), inverseJoinColumns = @JoinColumn(name = "acknowledgement_id"))
    @OrderBy("name")
    private Set<Acknowledgement> acknowledgements = new HashSet<Acknowledgement>();

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "company_industry", joinColumns = @JoinColumn(name = "company_id"), inverseJoinColumns = @JoinColumn(name = "industry_id"))
    @OrderBy("name")
    private Set<Industry> industries = new HashSet<Industry>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
    private Set<CompanyService> companyServices = new HashSet<CompanyService>();

    @OneToMany(fetch = FetchType.LAZY, targetEntity = Review.class, mappedBy = "company")
    private Set<Review> reviews = new HashSet<Review>();

    @OneToMany(fetch = FetchType.LAZY, targetEntity = Like.class, mappedBy = "company")
    private Set<Like> likes = new HashSet<Like>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
    private Set<AccountCompany> accountCompanies = new HashSet<AccountCompany>();
}

2 个答案:

答案 0 :(得分:5)

在遇到同样的问题和谷歌搜索后,我发现它是一个Hibernate错误: https://hibernate.atlassian.net/browse/HHH-9230

但似乎他们似乎并没有努力......这个问题没有受让人: - (

Hibernate的人似乎并不太关心他们的JPA实现......他们有很长时间的实时错误,似乎他们不打算修复它们: - (

答案 1 :(得分:3)

尝试使用索引参数而不使用@EntityGraph:

@Query("SELECT c FROM Company c WHERE c.id IN ?1")
List<Company> findByCompanyIdsForSearchResults(Set<Integer> companyIds);

如果它与index参数一起使用,请尝试添加@EntityGraph并查看它是否正常工作。

至于EntityGraph,您必须了解您正在生成的笛卡尔积问题:

@NamedAttributeNode(value = "acknowledgements"),
@NamedAttributeNode(value = "industries"),
@NamedAttributeNode(value = "companyServices", subgraph = "companyServices")

所有这些关联都是一对多的关系,因此当您获取公司时,您最终会得到一个笛卡尔积:

  • 公司
  • 确认
  • 行业
  • CompanyService

这将表现得非常糟糕,你应该总是加入FETCH at most one one-to-many association

我建议您删除EntityGraph并使用JOIN FETCH进行所有多对一和最多一对多的关联。

要初始化其他关联,您可以: