java - JPA 整洁架构

标签 java jpa design-patterns architecture clean-architecture

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

enter image description here

框架应该在最顶层。所以我使用适配器模式和依赖倒置来放置 org.springframework.data.repository.CrudRepository 在最顶层。但是,如果实体在中心,框架在最顶层?


例子: 演示实体:

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>{    
}

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

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

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

最佳答案

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

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

关于java - JPA 整洁架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576738/

相关文章:

java - 从 JPA 注释生成 DDL

java - 如何在Spring Gradle项目中将Lombok与JPA元模型一起使用?

oop - 是否使用 has-a(组合)或 is-a(继承)对汽车对象(及其部件,如引擎)进行建模?

java - 使用数组绘制 jFreechart 时出现问题

java - Google 应用程序引擎分析器

java - 合并配置库

java - JPA 删除子级会删除父级

c# - 我怎样才能让父类知道注入(inject)类的变化

c++ - 对不同的参数使用工厂方法模式

Java 编译器要求输入分号