首页 > 解决方案 > 从 HibernateCompositeUserType 查询字段时出现 IllegalArgumentException

问题描述

我们使用 Spring Data JPA (v2.0.8.RELEASE) 和 Hibernate (v5.2.x) 作为实现。我们注意到 Spring Data JPA 在尝试查询映射为CompositeUserType.

想象一下下面的类:

public class Currency {
    private String code;
    private int decimalPlaces;
    // getters and setters
}

以下示例使用此类作为CompositeType

public class A {

    @Type(type = "CurrencyUserType")
    @Columns(
            columns = {
                    @Column(name = "CODE",
                    @Column(name = "DECIMAL_PLACES"
            }
    )
    private CurrencyUnit currency;
    // getters and setters and constructor
}

Spring 数据存储库如下所示:

public class ARepository extends CrudRepository<A, Long> {

    Collection<A> findByCurrencyCode(String code);

}

但是,当我尝试执行findByCurrencyCode查询时,会引发以下异常:

java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Collection ARepository.findByCurrencyCode(java.lang.String)! Illegal attempt to dereference path source [null.currency] of basic type
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:82)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:208)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:553)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:546)

Hibernate 似乎期望我们用一个对象来查询A类。Currency但这意味着我们必须始终指定此对象中的所有字段。

作为替代方案,我们可以@Embeddable从 Currency 类中创建一个,因为它工作正常。不幸的是,我们不想这样做,因为这会将 Currency 类与 JPA 注释联系起来。我们想避免这种情况,因为我们想在不知道 JPA 的模块中重用该类(我们正在以一种干净的架构风格实现我们的应用程序)。

标签: hibernatespring-data-jpaspring-datacomposite-primary-key

解决方案


推荐阅读