【问题标题】:Spring Boot Common JPA repository classSpring Boot Common JPA 存储库类
【发布时间】: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


【解决方案1】:

看起来,您正在尝试做一些 @Profile 注释可以帮助您的事情。如果我是你,我会保留一个通用接口(不是类)并让 IConfigRepository 扩展它。然后你可以用@Profile 注解标记IConfigRepository。如果将来您必须编写模拟接口,您还应该使用@Profile 注释对其进行标记,并且您可以通过将相应的配置文件设置为活动来随时在这些接口之间切换。

@Repository
@Profile("config")
public interface IConfigRepository extends CommonRepository, JpaRepository<Config,Integer> {  
}

public interface CommonRepository {  
}

@Service
public class ServiceA {
  public final CommonRepository commonRepository;

   public ServiceA(CommonRepository commonRepository) {
       this.commonRepository = commonRepository
   }

  ...
}

【讨论】:

    猜你喜欢
    • 2021-11-07
    • 2018-08-06
    • 2021-04-16
    • 2015-12-15
    • 2018-06-26
    • 2017-04-23
    • 2019-01-23
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多