使用 spring 数据,我有两个共享相同结构的表。 这两个表由两个不同的实体表示,它们继承自同一类:
@MappedSuperclass
public abstract class SuperEntity<T extends SuperEntity> {
// ...
}
@Table(name = "FOO")
@Entity
public class Foo extends SuperEntity<Foo> {
// ...
}
@Table(name = "BAR")
@Entity
public class Bar extends SuperEntity<Bar> {
// ...
}
我还有一个通用存储库,我想用它来分解请求逻辑,以及两个子存储库:每个表一个。
public interface GenericEvtRepository <T extends SuperEntity<?>> extends JpaRepository<T, String> { }
public interface FooRepository extends GenericEvtRepository<Foo> {}
public interface BarRepository extends GenericEvtRepository<Bar> {}
我想向此存储库添加实际的查询实现(即使用 EntityManager/Criteria)。 因此,我尝试根据我的一般情况调整自定义存储库策略
@Repository
public class GenericEvtRepositoryImpl<T extends SuperEntity<?>> extends SimpleJpaRepository<T, String> implements GenericEvtRepository<T> {
@PersistenceContext
EntityManager entityManager;
// Some logic using entityManager
public SuperEntity myCustomRequest() { /*...*/ }
}
但是我的应用程序无法启动,但异常(exception):
org.springframework.data.mapping.PropertyReferenceException: No property myCustomRequest found for type Foo!
不确定我做错了什么,但 Spring 似乎认为 myCustomRequest 是我的实体的属性,而不是方法。
我正在使用 spring-boot 1.5.6 和 spring-data-jpa 1.11.6。
最佳答案
幸运的是,我能够重现您的问题,
spring推荐如何指定自定义存储库实现here在 Spring 文档中。
所以,你可以做如下的事情,
public interface CustomEntityRepository<T extends SuperTag<?>>
public interface FooRepository extends JpaRepository<Foo, Integer>, CustomEntityRepository<Foo>
public interface BarRepository extends JpaRepository<Bar, Integer>, CustomEntityRepository<Bar>
并定义 CustomEntityRepository<T extends SuperTag<?>>
的通用实现如下,
@Repository
// NOTE: Implementation name must follow convension as InterfaceName + 'Impl'
public class CustomEntityRepositoryImpl<T extends SuperTag<?>> implements
CustomEntityRepository<T> {
@PersistenceContext
private EntityManager entityManager;
// Generic custom implementation here
}
Spring 自动检测自定义接口(interface)的实现 CustomEntityRepository
基于实现类命名约定。
关于java - 自定义通用 Spring 数据存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57742381/