JPA Example 基本使用使用实例

一、相关接口方法

    在继承JpaRepository接口后,自动拥有了按“实例”进行查询的诸多方法。这些方法主要在两个接口中定义,一是QueryByExampleExecutor,一个是JpaRepository,如下所示:
复制代码
public interface QueryByExampleExecutor<T> { 
<S extends T> S findOne(Example<S> example); //根据“实例”查找一个对象。
<S extends T> Iterable<S> findAll(Example<S> example); //根据“实例”查找一批对象
<S extends T> Iterable<S> findAll(Example<S> example, Sort sort); //根据“实例”查找一批对象,且排序
<S extends T> Page<S> findAll(Example<S> example, Pageable pageable); //根据“实例”查找一批对象,且排序和分页
<S extends T> long count(Example<S> example); //根据“实例”查找,返回符合条件的对象个数
<S extends T> boolean exists(Example<S> example); //根据“实例”判断是否有符合条件的对象
}
复制代码
@NoRepositoryBean public interface JpaRepository<T, ID extends Serializable> 
  extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
 ...... 
@Override 
<S extends T> List<S> findAll(Example<S> example); //根据实例查询 
@Override 
<S extends T> List<S> findAll(Example<S> example, Sort sort);//根据实例查询,并排序。 
}
复制代码


返回单一对象精准匹配:
ProductCategory productCategory = new ProductCategory();

productCategory.setCategoryId(111);

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

ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryName("喜欢");
 //创建匹配器,即如何使用查询条件
ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("categoryName",,ExampleMatcher.GenericPropertyMatchers.endsWith())//endsWith是categoryName 结尾为喜欢的数据
        .withMatcher("categoryName",ExampleMatcher.GenericPropertyMatchers.startsWith())   //
.withIgnorePaths("isFace");//isFace字段不参与匹配
//创建实例
Example<ProductCategory> example =Example.of(productCategory,exampleMatcher);

//查询
List<ProductCategory> one = repository.findAll(example);
System.out.println(one);


原文地址:https://www.cnblogs.com/tangyb/p/8999767.html