gpt4 book ai didi

java - 存储库和服务层之间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:31:04 24 4
gpt4 key购买 nike

我查看了一些相关问题,但仍然看不出存储库层和服务层之间有太大区别。所以给出这个例子我想它应该是这样的,如果不是请告诉我为什么?

public interface ProductRepository extends CrudRepository<Product, Long>{

public List<Product> findByName(String name);
public List<Product> findByPrice(Double price);
}

public interface ProductService {

public List<Product> findAll();
public Product findById(Long id);
public Product save(Product product);
public void delete(Product product);
public List<Product> findByName(String name);
public List<Product> findByPrice(Double price);
}

ProductService 的实现将使用 ProductRepository 来实现这些方法。据我了解http://docs.spring.io/spring-data/jpa/docs/1.3.0.RELEASE/reference/html/jpa.repositories.html对存储库中方法的查询是自动生成的。在我的示例中,方法在存储库和服务中重复出现,因此请解释需要更改的内容/原因?

最佳答案

您所有的业务逻辑都应该在服务层中。

对数据库(任何存储)的任何访问都应该转到存储库层。

让我们举个例子。您必须保存一个实体(人)。但在保存人物之前,您要确保人物的名字不存在。

所以验证部分应该到业务层。

在服务层

PersonRepository repository; 
public Person save(Person p){
Person p = findByName(p.getName();
if (p != null){
return some customException();
}
return repository.save(p);
}

public Person findByName(String name){
return repository.findByName(name);
}

在您的存储层中,只需专注于数据库操作。

您可以自己在 Repository Layer 中完成此操作。假设你已经在你的存储库中实现了这个,那么你的保存方法总是在保存之前进行检查(有时你可能不需要这样做)。

关于java - 存储库和服务层之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22963352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com