JPA实现泛型baseServcie+Mybatis

在开发的过程中,我们总无法避免不同的实体类会去实现相同的操作(增删查改,分页查询等),因此在开发时,我们期望泛型将通用的方法进行包装,使我们能够专注于实体类自身的独特方法,而非一般性常用且重复性高的方法。

 

泛型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.

上一篇:Windows系统参数配置


下一篇:JDK8接口新特性