spring-boot - 将自定义方法添加到实现另一个存储库接口的抽象类,以便在一个地方同时拥有通用方法和自定义方法
问题描述
实体:
@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();
// ...
}
}
我可以这样做吗?或者我怎样才能做到这一点。
解决方案
您可以通过以下方式实现它:
interface CustomPersonRepository {
void customMethod();
}
@Repository
class CustomPersonRepositoryImpl implements CustomPersonRepository { /* implementation */}
public interface PersonRepository
extends JpaRepository<Person , String>, CustomPersonRepository {
...
}
请注意,PersonRepository
扩展CustomPersonRepository
.
现在您可以注入PersonRepository
,它将具有来自CustomPersonRepositoryImpl
推荐阅读
- frontend - 大师/学生艺术家的“家谱”集成
- jenkins - 多个参数的 Jenkins 参数化项目
- python - 如何使用python将字典列表创建为单个字典?
- android - 如何在 Recyclerview 中使用 SelctionTracker 禁用拖动到选择?
- c# - Azure Web 应用未从配置选项卡中获取值
- jinja2 - 从 SaltStack 中的 load_yaml 块访问列表变量
- json - docxtemplater:表格在循环中消失
- javascript - 你好!我想一次性删除容器内的所有 div。如果没有内部 div 的任何类或 id,我怎么能做到这一点?
- xml - 尝试使用 net core / net 5 连接 SOAP 服务
- sql - 有没有办法通过改变输入来循环函数并合并所有结果?