我查看了一些相关的问题,但仍然没有看到存储库和服务层之间有太大区别。所以给出的例子我想它应该看起来像这样,如果不是请告诉我为什么?
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 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);
}
在您的存储库层中,只需专注于数据库操作。
您可以在存储库层中自行完成此操作。假设您已经在存储库中实现了这一点,那么您的保存方法总是在保存之前进行检查(有时您可能不需要这样做)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)