JPA Example 基本使用使用实例

一、相关接口方法

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

 

复制代码
@NoRepositoryBean public interface JpaRepository 
  extends PagingAndSortingRepository, QueryByExampleExecutor {
 ...... 
@Override 
 List findAll(Example example); //根据实例查询 
@Override 
 List findAll(Example example, Sort sort);//根据实例查询,并排序。 
}
复制代码

 



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

productCategory.setCategoryId(111);

//将匹配对象封装成Example对象
Example example =Example.of(productCategory);
//根据id:111精准匹配对象,id必须是唯一主键,查出2条会报错
Optional 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 example =Example.of(productCategory,exampleMatcher);

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


转载于:https://www.cnblogs.com/tangyb/p/8999767.html

你可能感兴趣的:(JPA Example 基本使用使用实例)