jpa 动态查询条件 数组,JPA条件查询中的条件where子句

I am facing an issue for JPA criteria query. How can I add multiple where clause in my Criteria Query with if else...

My Requirement is:

CriteriaBuilder builder = getEm().getCriteriaBuilder();

CriteriaQuery query = builder.createQuery(Object.class);

// From

Root entity= query.from(EntityClass.class);

// Select

query.multiselect(entity.get("id").get("col1"),entity.get("id").get("col2"));

// Where

Predicate p1 = builder.and(builder.equal(entity.get("col3"), value3));

Predicate p2 = builder.and(builder.equal(entity.get("col4"), value4));

Predicate p3 = builder.and(builder.equal(entity.get("col5"), value5));

if(someCondition1){

query.where(p1);

}else if(someCondition2){

query.where(p1);

}

query.where(p3);

In above code the statement query.where(p3); replaces previously set where clause condition p1 and p2. What the alternate I found is conjunct like below

if(someCondition1){

query.where(p1, p3);

}else if(someCondition2){

query.where(p2, p3);

}else{

query.where(p3);

}

But that is not a good approach, because when there are many if-else this becomes very bad to write repeating codes. Can any one have a solution for this?

解决方案

You can create a Predicate array to store your conditional Predicates and then add it to the where clause:

List predList = new LinkedList();

if(someCondition1){

predList.add(p1);

}else if(someCondition2){

predList.add(p2);

}

predList.add(p3);

Predicate[] predArray = new Predicate[predList.size()];

predList.toArray(predArray);

query.where(predArray);

This allows to dynamically add any kind of predicate.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值