本文介紹了存儲庫和服務層之間的區別的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我查看了一些相關問題,但我仍然看不出存儲庫和服務層之間有太大區別。所以給出這個例子,我想應該是這樣的,如果不是,請告訴我為什么?
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本身中完成此操作。假設您已經在存儲庫中實現了這一點,那么您的保存方法總是在保存之前進行檢查(有時您可能不需要這樣做)。
這篇關于存儲庫和服務層之間的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,