一、相关接口方法
在继承JpaRepository接口后,自动拥有了按“实例”进行查询的诸多方法。这些方法主要在两个接口中定义,一是QueryByExampleExecutor,一个是JpaRepository,如下所示:
public interface QueryByExampleExecutor{ S findOne(Exampleexample); //根据“实例”查找一个对象。IterablefindAll(Exampleexample); //根据“实例”查找一批对象IterablefindAll(Exampleexample, Sort sort); //根据“实例”查找一批对象,且排序PagefindAll(Exampleexample, Pageable pageable); //根据“实例”查找一批对象,且排序和分页long count(Exampleexample); //根据“实例”查找,返回符合条件的对象个数boolean exists(Exampleexample); //根据“实例”判断是否有符合条件的对象 }
@NoRepositoryBean public interface JpaRepositoryextends PagingAndSortingRepository , QueryByExampleExecutor { ...... @Override ListfindAll(Exampleexample); //根据实例查询 @OverrideListfindAll(Exampleexample, Sort sort);//根据实例查询,并排序。 }
返回单一对象精准匹配:
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryId(111);
//将匹配对象封装成Example对象
Exampleexample =Example.of(productCategory);
//根据id:111精准匹配对象,id必须是唯一主键,查出2条会报错
Optionalone = 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字段不参与匹配
//创建实例
Exampleexample =Example.of(productCategory,exampleMatcher); //查询
Listone = repository.findAll(example);
System.out.println(one);