spring data jpa多條件查詢

2021-08-08 13:46:22 字數 2514 閱讀 6937

主要是工作中用到的關於jpa的條件查詢,使用了specification的predicate(斷言查詢)條件查詢代替原生sql或@query註解:

/**

* 展示列表和條件查詢(多條件查詢)

* @param status

* @param createtime

* @param ordernum

* @param modelname

* @param pageable

* @return

*/@override

public pagegetallordertaking(string status, string createtime, string ordernum, string modelname, pageable pageable)

if(null != modelname)

if(null != createtime && !""

.equals(createtime))else

} catch (parseexception e)

}if(null != ordernum && !""

.equals(ordernum))

if(stringutils.isnotempty(ordernum) & stringutils.isnotempty(modelname))else

}}else

return criteriabuilder.and(predicates.toarray(new predicate[predicates.size()]));}};

pagepage = orderrepository.findall(specification,pageable);

//組裝vo實體

listordervos = new arraylist<>();

page.getcontent().stream().foreach(order -> );

pagevopage = new pageimpl<>(ordervos,pageable,page.gettotalelements());

return vopage;

}

//categoryname是我們需要查詢的列(字段)

subquerycategoryname = criteriaquery.subquery(string.class);

//root(實體對應的資料庫表)

rootcategoryroot = categoryname.from(category.class);

//通過單錶的查詢需要的列並新增where條件 categoryname.select(categoryroot.get("categorynum")).where(criteriabuilder.like(categoryroot.get("name"),"%"+modelname+"%"));

//同樣categorynum是我們需要查詢的列(字段),但不在同在一張表中

subquerycategorynum = criteriaquery.subquery(string.class);

rootgoodsroot = categorynum.from(goods.class); categorynum.select(goodsroot.get("id")).where(goodsroot.get("categorynum").in(categoryname));

predicate1 = criteriabuilder.in(root.get("goodsid")).value(categorynum);

predicate p1 = criteriabuilder.equal(root.get("status"),order.status

.valueof("待審核"));

private

final

static string time_min = " 00:00:00 000";

private

final

static string time_max = " 23:59:59 999";

private

final

static string date_format = "yyyy-mm-dd hh:mm:ss sss";

//查詢是否在兩個時間段之間

predicates.add(criteriabuilder.greaterthanorequalto(root.get("createtime"), new ******dateformat(date_format).parse(createtime + time_min)));

predicates.add(criteriabuilder.lessthanorequalto(root.get("createtime"), new ******dateformat(date_format).parse(createtime + time_max)));

Spring Data Jpa 多條件排序

簡單的常用的就不多說了,這裡紀錄下專案中用到的幾種排序場景sort sort issnapshot new sort sort.direction.desc,istop createtime new sort sort.direction.asc,state createtime sort sort...

Spring data jpa多表查多條件查詢

現有如下場景,需要根據a表的check code欄位和b表的store code check result欄位組合查詢,a表與b表的關聯關係為一對多。為了簡化查詢引數,我們對查詢引數進行了封裝,抽出了公共的querycondition public class querycondition publ...

八 Spring Data JPA多條件分頁查詢

多條件查詢 public page pagequery label label,integer page,integer size 標籤狀態 if stringutils.isnotblank label.getstate predicate parr newpredicate list.size ...