【发布时间】:2021-05-19 08:02:53
【问题描述】:
我有许多 JPA 存储库类,我想创建一个公共类,我将在其中创建相应存储库的 getter 方法,我将在服务层中使用该公共类。 那么请您指导我如何实现这一目标的最佳实践?
在这里我通过示例代码分享我的想法,
JPA 存储库
@Repository
public interface IConfigRepository extends JpaRepository<Config, Integer> {
}
public interface IBusinessRepository extends JpaRepository<Business, Integer> {
}
Repo Factory(所有存储库的通用类)
public class RepoFactory {
@Autowired
private IConfigRepository configRepo;
@Autowired
private IBusinessRepository businessRepo;
public IConfigRepository getConfigRepository() {
return configRepo;
}
public IBusinessRepository getBusinessRepository() {
return businessRepo;
}
}
服务类
@Service
public class ServiceA {
public final RepoFactory repoFactory;
public ServiceA(RepoFactory repoFactory) {
this.repoFactory = repoFactory
}
@Transactional(rollbackOn = Exception.class)
public void saveOrUpdate(Config config) {
repoFactory.getConfigRepository().save(config);
}
}
@Service
public class ServiceB {
public final RepoFactory repoFactory;
public ServiceB(RepoFactory repoFactory) {
this.repoFactory = repoFactory
}
@Transactional(rollbackOn = Exception.class)
public void saveOrUpdate(Business reqBusiness) {
repoFactory.getBusinessRepository().save(reqBusiness);
}
}
谢谢大家提前帮助我。
【问题讨论】:
-
这个行动的最终目标是什么?
-
最终目标是我应该使用一个通用类(例如 RepoFactory)来访问所有存储库类。可能吗?遵循这种做法是否良好?
-
这是一种好的做法吗? 实际上不是。每个服务应该只包含将在那里使用的存储库。利润在哪里?无论如何,所有 spring 存储库都在上下文中。我能想象的像你这样的唯一情况是通用定制。如果您真的需要它,请查看that topic
标签: java spring spring-boot spring-data-jpa