JPA的Repository详解
JPA的Repository详解
JPA
Spring Data是Spring提供的操作数据的框架,Spring Data JPA是Spring Data的一个模块,通过Spring data 基于jpa标准操作数据的模块。
Spring Data的核心能力,就是基于JPA操作数据,并且可以简化操作持久层的代码。
它使用一个叫作Repository的接口类为基础,它被定义为访问底层数据模型的超级接口。而对于某种具体的数据访问操作,则在其子接口中定义。
Spring Data可以让我们只定义接口,只要遵循spring data的规范,就无需写实现类,不用写sql语句直接查询数据。
JpaRepository
JpaRepository继承PagingAndSortingRepository,添加了一组JPA规范相关的方法。对继承父接口中方法的返回值进行了适配,因为在父类接口中通常都返回迭代器,需要我们自己进行强制类型转化。而在JpaRepository中,直接返回了List。
开发中最常用JpaRepository
泛型,第一个参数为要操作的实体类,第二个参数为该实体类的主键类型
public interface SpuRepository extends JpaRepository<Spu, Long> {
Spu findOneById(Long id);
Page<Spu> findByCategoryIdOrderByCreateTimeDesc(Long cid, Pageable pageable);
Page<Spu> findByRootCategoryIdOrderByCreateTime(Long cid, Pageable pageable);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
JpaRepository数据层
一步一步学SpringDataJpa——JpaRepository查询功能
https://blog.csdn.net/xfx_1994/article/details/104921234
public interface SpuRepository extends JpaRepository<Spu, Long> {
Spu findOneById(Long id);
Page<Spu> findByCategoryIdOrderByCreateTimeDesc(Long cid, Pageable pageable);
Page<Spu> findByRootCategoryIdOrderByCreateTime(Long cid, Pageable pageable);
}
一步一步学SpringDataJpa——JpaRepository查询功能 https://blog.csdn.net/xfx_1994/article/details/104921234