JPA分页查询与条件分页查询

整合JPA和使用方法见:整合JPA
继承JpaRepository接口后,自动拥有了按“实例”进行查询的诸多方法。先来列举常用的一些方法

@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
        //无条件查询 获取整个表 相当于 SELECT * FROM table_name;
    List<T> findAll();

    //增加排序
    List<T> findAll(Sort sort);
        //通过一个id序列获取列表
    List<T> findAllById(Iterable<ID> ids);

    //通过id查询
    T getOne(ID id);

    ...
}

无条件分页查询可以使用PagingAndSortingRepository中的方法

@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {

    //通过传入一个遵循pageale协议的对象 获取某一页的数据
    Page<T> findAll(Pageable pageable);
}

有条件分页查询可用QueryByExampleExecutor中的方法

public interface QueryByExampleExecutor<T> {

    ///根据“实例”查找一批对象,且排序和分页
    <S extends T> Page<S> findAll(Example<S> example, Pageable pageable);

    ... 
}

@Autowired
public ProductRespository productRespository;

我们自动注入的Respository输入.find会显示如下列表,基本上查询也就用下面这些方法就够了

3284263-37820123c15c9f33.png
image.png

如果需要其他简单的列表查询可直接在我们自己定义的ProductRespository接口中添加方法,也是可以直接调用查询 不需要写实现

public interface ProductRespository extends JpaRepository<Product,Integer> {
    List<Product> findAllByVendorId(Integer vendorId);
}

实例讲解一下Example和Pageable的用法
///返回单一对象精准匹配:

Product product= new Product();

product.setId(1);

//将匹配对象封装成Example对象
Example<Product> example =Example.of(product);
//根据id:111精准匹配对象,id必须是唯一主键,查出2条会报错
Optional<Product> one = repository.findOne(example);

///多条件,返回Page对象:

///Sort.Direction是个枚举有ASC(升序)和DESC(降序)
Sort.Direction sort =  Sort.Direction.ASC;
///PageRequest继承于AbstractPageRequest并且实现了Pageable
///获取PageRequest对象 index:页码 从0开始  size每页容量 sort排序方式 "id"->properties 以谁为准排序
Pageable pageable = PageRequest.of(index, size, sort, "id");
///要匹配的实例对象
Product exPro = new Product();
exPro.setVendorId(id);
///定义匹配规则 匹配"vendorId"这个属性 exact 精准匹配
ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("vendorId",ExampleMatcher.GenericPropertyMatchers.exact());
Example<Product> example = Example.of(exPro,exampleMatcher);
Page<Product> page = productService.productRespository.findAll(example,pageable);
///获取总页数
page.getTotalPages();
///获取总元素个数
page.getTotalElements();
///获取该分页的列表
page.getContent();

备注:
ExampleMatcher:

///创建一个匹配器  默认全匹配
static ExampleMatcher matching() {
        return matchingAll();
    }
///匹配路径和匹配模式
ExampleMatcher withMatcher(String propertyPath, GenericPropertyMatcher genericPropertyMatcher);

3284263-b3fe1a5974c72b4b.png
image.png

猜你喜欢

转载自blog.csdn.net/weixin_33725270/article/details/87233639
今日推荐