簡體   English   中英

使用 Criteria Builder API 自定義查詢加入 JPA

[英]Custom Query Join in JPA using Criteria Builder API

目前我正在這樣做:

List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity) {
    String queryString = "SELECT table1.* FROM table1 " 
                    + "JOIN table2 t2 ON table1.id=t2.table1_id";

    if (table1Entity.getName() != null) {
          queryString +=" where name like ?";                 
    }

    Query query = em.createNativeQuery(queryString, Table1Entity.class);

    if (table1Entity.getName() != null) {
        query.setParameter(1, table1Entity.getName())    
    }

    return query.getResultedList();
}

如果我想在這個連接中檢查更多參數,這將很快變成很多 if 語句,並且正確設置參數會非常復雜。

我知道我可以使用標准 Builder API 來檢查參數,如下所示:

if(table1Entity.getName() != null) {
    table1EntitySpecification = (root, query, criteriaBuilder)
                         -> criteriaBuilder.like(
                            criteriaBuilder.lower(root
                           .get("name")),
                           ("%" + table1Entity.getName() + "%")
                           .toLowerCase());;
}

然后讓他們全部獲得:

findAll(table1EntitySpecification)和來自simpleJPARepositoryfindAll 現在我可以將它們與.or.and等鏈接在一起,避免第二次設置參數和檢查null

但是我該如何加入criteria APi

我知道我可以在我的@Repository中有這樣的東西:

@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);

但由於name是可選的(可以是null ),我不能只將它留在@Query中。

避免使用本機查詢以及必須檢查許多參數以避免使用if語句的最佳解決方案是什么?

我不知道我是否完全得到你的問題,但關於空值的可能性,以及使用 CRUD 存儲庫,你總是可以像之前一樣做一個 null 檢查:

@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id WHERE table1.id is not null", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);

根據您要實現的目標,您始終可以使用類似的檢查來編寫查詢,例如(與您的代碼無關):

@Query("SELECT c FROM Certificate c WHERE (:id is null or upper(c.id) = :id) "
           + "and (:name is null or upper(c.name) = :name)")
List<Table1> findStuff(@Param("id") String id,
                       @Param("name") String name);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM