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);



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM