我想编写作用于例如从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)
答案 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();