zoukankan      html  css  js  c++  java
  • 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);


  • 相关阅读:
    mysql的CURRENT_TIMESTAMP【转】
    php开发中emoji表情的问题3种方法轻松处理【转】
    JavaScript 正则表达式【转】
    使用 内置函数strtok()函数实现 loadrunner 字符串替换
    python打开文件失败,报错'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence
    txt文本程序 打开python文件 另存为原来的文件名,不能覆盖原来的文件解决
    linux 文件解压
    tar.xz 解压
    设置xampp开机自动启动
    Can’t connect to local MySQL server through socket的解决方法
  • 原文地址:https://www.cnblogs.com/tangyb/p/8999767.html
Copyright © 2011-2022 走看看