存储库和服务层之间的区别 [英] Difference between Repository and Service layer
本文介绍了存储库和服务层之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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 It本身中完成此操作。假设您已经在存储库中实现了这一点,那么您的保存方法总是在保存之前进行检查(有时您可能不需要这样做)。这篇关于存储库和服务层之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文