java - 自定义通用 Spring 数据存储库

标签 java spring spring-data-jpa spring-data

使用 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。

Minimal reproductible exemple

最佳答案

幸运的是,我能够重现您的问题,

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/

相关文章:

spring-boot - 我收到错误 Parameter 0 of constructor required a single bean, but 2 were found 但其中一个 "found"的 bean 已被我删除

spring-boot - 用于比较日期的 Spring Boot JPA 规范

java - 无法在泛型类中调用实体的保存

java - 使用文件中的字符串创建对象

java - 在java中使用switch语句for循环和while循环做一个简单的数学测验

spring - camunda 中的 Receivetask 未按预期工作

java - pdf 文件无法从 ubuntu 16.04 的 jar 中打开

Spring MVC 测试 3.2.2 由于某些奇怪的原因失败 "flash().attributeExists"断言

java - 添加 RedirectAttributes 参数导致 Spring MVC Controller 方法中出现 "Model has no value for key"异常

java - 如何设置 Spring/HIbernate JPA @Entiry 创建自动递增列(无 id)