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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值