我正在根据 Clean Architecture 重构微服务:
框架应该在最顶层。所以我使用适配器模式和依赖倒置来放置
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/