JPA自定義 Repository 方法
阿新 • • 發佈:2019-02-20
如果不使用SpringData的方法,想要自己實現,該怎麼辦呢?
定義一個介面: 宣告要新增的, 並自實現的方法
提供該介面的實現類: 類名需在要宣告的 Repository 後新增 Impl, 並實現方法
宣告 Repository 介面, 並繼承 1) 宣告的介面
注意: 預設情況下, Spring Data 會在 base-package 中查詢 "介面名Impl" 作為實現類. 也可以通過 repository-impl-postfix 聲明後綴.
這張圖是類與介面之間的關係
下面是具體的實現:
包結構
類與介面之間的關係程式碼
public interface PersonRepositoiry extends JpaRepository<Person, Integer> ,PersonDao{
public interface PersonDao {
void test();
}
@Repository
public class PersonRepositoiryImpl implements PersonDao{
@PersistenceContext
private EntityManager em;
@Override
public void test() {
//只是用來測試
Person person = em.find(Person.class, 1);
System.out.println(person);
}
}
測試程式碼
@Test
public void testCustomerRepositoryMethod() {
personRepositoiry.test();
}
經過實踐發現:
- XXXRepositoryImpl 與XXXRepository前面的名字必須相同,後面的也需要按照規則寫
- 若將XXXRepositoryImpl與XXXRepository介面放在同意包下,XXXRepositoryImpl不需要新增@Repository註解,但是當XXXRepositoryImpl與XXXRepository介面不在同一包下,需要在在XXXRepositoryImpl類上加@Repository註解進行修飾