在開發的過程中,我們總無法避免不同的實體類會去實現相同的操作(增刪查改,分頁查詢等),因此在開發時,我們期望泛型將通用的方法進行包裝,使我們能夠專注於實體類自身的獨特方法,而非一般性常用且重複性高的方法。
泛型Base<T,V>我們通過繼承jparepository<T,V >進行實現。通過jpa的部分封裝方法,能使我們減少重複性程式碼的編寫,並且我們可以在泛型介面中加入我們自己想定義的方法。
@NoRepositoryBean //註解 不例項化該類,否則啟動報錯
public interface BaseRepository<T,V> extends JpaRepository<T, V>,JpaSpecificationExecutor<T> { //public void update(T t);
List<T> list(PageRequestForm form); Page<T> find(PageRequestForm form); }
之後對於實體類單獨的方法,因為我在與小夥伴協作開發,所以公共約定使用Mybatis進行編寫。
@Mapper
public interface ArticleDao {
@Select("SELECT c.id, u.name, u.portrait, c.content, c.create_date" +
" FROM goods_comment AS c" +
" LEFT JOIN user AS u ON u.id = c.user_id" +
" WHERE c.type = #{type} AND c.type_id = #{typeId}" +
" ORDER BY c.create_date DESC LIMIT #{current}, #{count}")
List<Map<String,Object>> getComment(@Param("type") Integer type, @Param("typeId") Long typeId,
@Param("current") int current, @Param("count") int count); }
這麼做的好處就在於:我們只需要關注某些實體類所特有的方法,基礎的操作交給jpa和我們之前自定義實現的方法完成就行。比如我在對Article的公共類實現時,只需要將對應的Article注入到泛型中,
之後如果有其他的實體類,比如Address,同樣注入相應的介面即可。在controller層,我們只需要自動裝配@Autowirse ArticleBase(AddressBase),即可使用實體類對應的公共方法。
/*
這裡是Article實體類公共方法,繼承了泛型BaseRepository<T,V>,其中T是實體類,V是主鍵 如果是其他類,比如Address就是:
@Repository
interface ArticleBase extends com.framework.jpa.BaseRepository<Address,Integer> {} */
@Repository
interface ArticleBase extends com.framework.jpa.BaseRepository<Article,Integer> {} //@Repository
//interface AddreseBase extends com.framework.jpa.BaseRepository<Address,Integer> {}
具體可見我的gtihub: https://github.com/LZKZD/JPA-base-Mybatis .
歡迎交流和star.