首页 > 解决方案 > 将自定义方法添加到实现另一个存储库接口的抽象类,以便在一个地方同时拥有通用方法和自定义方法

问题描述

实体:

@Entity
public class Person {
    @Id
    private String id;
    private String name;
    private int age;
}

扩展 JpaRepository 的存储库:

@Repository
public interface PersonRepository extends JpaRepository<Person , String> {
    @Query(...)
    List<Something> findSomethingBySomething();
    List<Person> findPersonByNameAndAge(String name, int age);
}

因此,我想要一个 CustomRepository,例如该存储库具有 PersonRepository (继承的)方法以及具有标准构建器查询的自定义方法。

像这样的东西。

@Repository
public abstract class PersonRepositoryCustom implements PersonRepository {
    @Autowired
    EntityManager entityManager;
    
    public void customMethod() {
        // uses criteria builder, criteria query to create custom query using 
    }
}

在服务中,我只想使用那个 PersonRepositoryCustom 以便我可以从 PersonRepository 获取所有方法以及从 PersonRepositoryCustom 获取方法;

像这样的东西

@Service
public class Service {
    @Autowired
    PersonRepositoryCustom personRepository;

// I want to access all methods like
    public void method() {
        personRepository.save();
        personRepository.findPersonByNameAndAge("name", 20);
        personRepository.findSomethingBySomething();
        personRepository.customMethod();
        personRepository.findById();
        // ...
    } 
}

我可以这样做吗?或者我怎样才能做到这一点。

标签: spring-boothibernatespring-data-jpa

解决方案


您可以通过以下方式实现它:

interface CustomPersonRepository {
  void customMethod();
}

@Repository
class CustomPersonRepositoryImpl implements CustomPersonRepository { /* implementation */}

public interface PersonRepository 
      extends JpaRepository<Person , String>, CustomPersonRepository {
    ...
}

请注意,PersonRepository扩展CustomPersonRepository.

现在您可以注入PersonRepository,它将具有来自CustomPersonRepositoryImpl


推荐阅读