0

我想编写作用于例如从 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 中遇到错误:

函数中的 apply (capture < ? extends org.springframework.data.jpa.repository.JpaRepository< ? extends javax.persistence.Entity,java.lang.Integer>>) 不能应用于 (.java_tests.database.TestEntityRepository)

4

1 回答 1

0

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

这样做的一般方法是创建接口(或抽象类)并TestEntity实现(或扩展)它。

public class BaseEntity { ... }

public class TestEntity extends BaseEntity { ... }

和方法

//---------------------------------------------------vvvvv-------
private Function<? extends JpaRepository<? extends BaseEntity, Integer>, Boolean> doSomeThing = integerJpaRepository ->
        integerJpaRepository.findAll().isEmpty();
于 2018-09-26T18:01:21.433 回答