Spring Data Jpa 自定義方法實現問題

轉自:http://blog.csdn.net/qq_23660243/article/details/43194465 
  最近項目中用到了spring Data JPA,在裏面我繼承了一個PagingAndSortingRepository的接口,期望的是利用Spring Data JPA提供的便利。同時我也希望自己有一個能定義自己方法的接口,因爲單純靠Spring Data JPA中提供的功能還是有很多業務邏輯實現不了,我必須自己實現。那麼問題來了:Spring Data JPA好處就是讓我們省去了實現接口的過程,按照他們給的命名規範他們會自動實現我們的業務邏輯,那我們自己實現的接口要怎麼注入到其中呢? 

   上網查找了好多資料,都沒有說的太詳細,更多的是照搬胡抄,這裏是我親自寫的,可能很多人會用到,不多說上代碼:

    自己的接口:

 

[java] view plain copy
 print?
  1. package com.mhc.dao;  
  2.   
  3. import org.springframework.stereotype.Repository;  
  4.   
  5. import com.mhc.entity.Person;  
  6.   
  7. @Repository  
  8. public interface DeviceCategoryDaoCustom {  
  9.     public Person getsFather(Person person);  
  10.   
  11. }  

   主接口:

[java] view plain copy
 print?
  1. public interface DeviceCategoryDao extends  
  2.         PagingAndSortingRepository<Person, String>, DeviceCategoryDaoCustom {  
  3.       
  4.   
  5. }  
  上面是我的接口繼承PagingAndSortingRepository、DeviceCategoryDaoCustom(我自己方法的接口)。然後我新建一個類來實現我自己的接口:
[java] view plain copy
 print?
  1. package com.mhc.dao;  
  2.   
  3. import javax.persistence.PersistenceContext;  
  4. import javax.transaction.Transactional;  
  5.   
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.data.repository.CrudRepository;  
  8. import org.springframework.data.repository.NoRepositoryBean;  
  9. import org.springframework.stereotype.Component;  
  10. import org.springframework.stereotype.Repository;  
  11. import org.springframework.stereotype.Service;  
  12.   
  13. import com.mhc.entity.Person;  
  14.   
  15. @Repository("crudRepositoryDaoCustom")  
  16. class DeviceCategoryDaoImpl implements DeviceCategoryDaoCustom {  
  17.   
  18.     @Transactional  
  19.     public Person getsFather(Person person) {  
  20.         // TODO Auto-generated method stub  
  21.         Person father = new Person();  
  22.         father = person.getParentPerson();  
  23.         return father;  
  24.     }  
  25. }  

在這裏有個需要注意的地方,就是用不用implements的問題,如果用的話,他就會調用編譯器的實現功能去實現我們自定義的接口也就是:DevicecategoryCustom。如果去掉的話,他會去實現DeviceCategoryDao,那麼會有人問,他怎麼去自己找的呢。事實上他是根據後面的Impl來尋找的。他不會提示@override,不過你寫相同的方法他還是會覆蓋(覆蓋主接口中的同名方法,如果有的話)DeviceCategoryDao中的同名方法。你可以去嘗試一下。

同時加上@Repository把他加入到Bean裏面,這樣下次用這個方法的時候Repository會自動找到他的(話說Spring團隊真心NB)。然後我們交給spring託管、測試。。。。。Ok  真心贊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章