【问题标题】:Custom generic spring data repository自定义通用弹簧数据存储库
【发布时间】:2020-01-04 15:09:11
【问题描述】:

使用 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() { /*...*/ }
}

但是我的应用程序没有启动,除了:

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

【问题讨论】:

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


    【解决方案1】:

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

    spring 文档如何推荐自定义存储库实现在 here 中指定。

    所以,你可以像下面这样,

    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&lt;T extends SuperTag&lt;?&gt;&gt; 定义 common 实现如下,

    @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 根据实现类命名约定自动检测自定义接口CustomEntityRepository 的实现。

    【讨论】:

    猜你喜欢
    • 2015-04-06
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多