首页 > 解决方案 > JPA 清洁架构

问题描述

我正在根据Clean Architecture重构微服务:

在此处输入图像描述

框架应该在最顶层。所以我使用了适配器模式和依赖倒置来 org.springframework.data.repository.CrudRepository达到最高层。但是,如果实体位于中心并且框架位于最顶层,如何使用@Entity(来自Java持久性A PI )来持久化我的实体?


示例:演示实体:

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;

@Entity
public class Demo implements Serializable {
    @Id
    @GeneratedValue
    private long id;
    
    @NotNull
    private String foo;

}

GenericRepostioryInterface(在用例层中)

public interface CrudRepositoryInterface<S,T> {
    public <U extends S> U save(U u) ;    
    public <U extends S> Iterable<U> saveAll(Iterable<U> itrbl) ;    
    public Optional<S> findById(T id) ;    
    public boolean existsById(T id) ;    
    public Iterable<S> findAll() ;    
    public Iterable<S> findAllById(Iterable<T> itrbl) ;    
    public long count() ;    
    public void deleteById(T id) ;    
    public void delete(S t);    
    public void deleteAll(Iterable<? extends S> itrbl) ;    
    public void deleteAll() ;  
}

一些用例:

    @Autowired
    private CrudRepositoryInterface<Demo,Long> demoRepository;
    ...
    
    private void deleteAll(){
      this.demoRepository.deleteAll();
    }
    ...

适配器(数据库层)

public interface DemoRepositoryAdapter extends CrudRepository<Demo,Long>,CrudRepositoryInterface<Demo,Long>{    
}

配置注入(我也把它放在数据库包/层中)

@Configuration
public class InjectRepositoryConfig {    
    @Bean
    public CrudRepositoryInterface<Demo,Long> animalOwnerRepository(@Autowired DemoRepositoryAdapter demoRepositoryAdapter){
        return demoRepositoryAdapter;
    }
}

到目前为止这工作正常,但我不确定如何从核心层中删除/替换/重构 JPA?

标签: javajpadesign-patternsarchitecture

解决方案


我认为这里的普遍混淆是由于术语实体的重载,它在不同的上下文中具有不同的语义。在 JPA 的上下文中,实体是表示表和 ORM 中的行的持久性抽象。在 Clean Architecture 的上下文中,实体是业务领域的抽象,完全独立于持久性。

它们可以在一个干净的架构中共存,但它们各自都有不同的用途。尝试将它们结合起来并在您的业务领域实体中利用 JPA 功能违反了清洁架构的原则,并将您的领域与您的持久性实现耦合在一起。


推荐阅读