我们正在使用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
类。但这意味着我们必须始终指定此对象中的所有字段。
作为替代方案,我们可以从Currency类中制作一个@Embeddable
,因为它可以正常工作。不幸的是,我们不希望这样做,因为这将Currency类与JPA注释相关联。我们想避免这种情况,因为我们想在不了解JPA的模块中重用该类(我们正在以“干净架构”样式实现我们的应用程序。)