如何在泛型中指定javax.persistence @Entity注释类?

时间:2018-09-26 16:23:19

标签: generics spring-data-jpa javax.persistence

我想编写作用于例如从Spring JpaRepository<TestEntity, Integer>扩展。

我尝试过: 实体:

import javax.persistence.Entity; 
import javax.persistence.Id;

@Entity
public class TestEntity {
    @Id
    Integer a;
    Integer b;
}

回购:

import org.springframework.data.jpa.repository.JpaRepository;

public interface TestEntityRepository extends JpaRepository<TestEntity,Integer> {}

一个服务类看起来像像这样:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.persistence.Entity;
import java.util.function.Function;

@Service
public class TestEntityService {

    @Autowired
    TestEntityRepository testEntityRepository;

    private Function<? extends JpaRepository<? extends Entity, Integer>, Boolean> doSomeThing = integerJpaRepository ->
        integerJpaRepository.findAll().isEmpty();

    public Boolean dbIsEmpty(){
        return doSomeThing.apply(testEntityRepository);
    }
}

但是,我在Intellij中遇到错误:

  

应用   (捕获<?扩展org.springframework.data.jpa.repository.JpaRepository <?扩展javax.persistence.Entity,java.lang.Integer >>)   在功能中无法应用   至   (.java_tests.database.TestEntityRepository)

1 个答案:

答案 0 :(得分:0)

要使用Function<? extends JpaRepository<? extends Entity, Integer>,您的TestEntity必须扩展实现实体,而不能注释。

执行此操作的一般方法是创建接口(或抽象类),并使TestEntity实现(或扩展)它。

public class BaseEntity { ... }

public class TestEntity extends BaseEntity { ... }

和方法

//---------------------------------------------------vvvvv-------
private Function<? extends JpaRepository<? extends BaseEntity, Integer>, Boolean> doSomeThing = integerJpaRepository ->
        integerJpaRepository.findAll().isEmpty();