JPA 多條件 多表查詢

2021-08-29 22:42:44 字數 2085 閱讀 6749

jpa對於簡單的查詢操作確實很給力,但是涉及到多表、多條件、分頁的場景就不是很好實現了。

可行的解決方案

1、多條件

public inte***ce baserepositoryextends jparepository, jpaspecificationexecutor
使用specification來實現條件的拼接

2、多表

資料量不大的情況,可以考慮檢視,檢視實體配置和表的沒有任何區別。

3、分頁

可以自行實現分頁邏輯,也可以使用框架的 pageable 類。

核心**示例

//	核心方法 拼接條件

public default predicate getpredocate(rootroot, criteriaquery<?> query, criteriabuilder cb,

dataqueryobject dqo)

// 如果註解中 name為空 則用欄位名稱作為屬性名

if(!stringutils.isempty(annotaion.name())) else

querytype = annotaion.type();

try catch (illegalargumentexception e) catch (illegalacces***ception e)

// 判斷字段型別是否為空

if(value == null && querytype.isnotcanbenull())

// 判斷註解中 的條件型別

switch (querytype)

for (object object : inlist)

predicates.add(ins);

break;

default:

break;

}}// 如果 為空 代表 沒有任何有效的條件

if(predicates.size() == 0)

object list = predicates.toarray();

predicate t = new predicate[predicates.size()];

predicate result = predicates.toarray(t);

return cb.and(result);

} public default pathgetrootbyqueryfiled(string queryfiled, rootroot) else

} public default pathgetrootbyqueryfiled(string queryfiled, pathpath) else }

public default pathgetrootbyqueryfiledstring(string queryfiled, rootroot) else

} public default pathgetrootbyqueryfiledstring(string queryfiled, pathpath) else }

public default pathgetrootbyqueryfiledcomparable(string queryfiled, rootroot) else

} public default pathgetrootbyqueryfiledcomparable(string queryfiled, pathpath) else

}

自定義註解

@retention(retentionpolicy.runtime)

@target(elementtype.field)

public @inte***ce queryfield

接收引數

@queryfield(type = querytype.equal, name = "redddlcode")

@apimodelproperty(value="***",name="redddlcode",example="s2344")

private string redddlcode;

JPA 多表左連線多條件分頁查詢

業務場景 主表 訂單表,與客戶表 產品表 物流表存在一對一關係,對映欄位為id,現需要根據訂單編號 訂單日期 客戶名稱 客戶編號 產品名稱 產品編號 快遞單號查詢該筆訂單,需要支援模糊查詢和分頁。order實體類中的需要進行一對一關係對映 onetoone joincolumn name expre...

JPA多條件查詢 分頁 區域性重新整理

使用多條件查詢 實體類 標明為實體類 entity 命名為一張表,如果db中沒有則新增一張表,若有則更新字段,name可以設定表名,若不設定,則與類同名 table name t collection public class collect public long getid public voi...

Jpa多表查詢

作業題目 api 商品列表 get sell buyer product list引數無 返回 建立訂單 post sell buyer order create 引數返回 訂單列表 get sell buyer order list 引數openid 18eu2jwk2kse3r42e2e pag...