JPA条件查询中的条件where子句

JPA条件查询中的条件where子句

本文介绍了JPA条件查询中的条件where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临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...

我的要求是:

CriteriaBuilder builder = getEm().getCriteriaBuilder();
CriteriaQuery<Object> query = builder.createQuery(Object.class);

// From
Root<EntityClass> 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);

在上面的代码中,语句query.where(p3);替换先前设置的where子句条件p1和p2.我发现的替代项与下面的相合

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

但这不是一个好方法,因为如果有很多if-else,那么编写重复代码将变得非常糟糕.有人可以为此提供解决方案吗?

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?

推荐答案

您可以创建一个谓词数组来存储条件谓词,然后将其添加到where子句中:

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

List<Predicate> predList = new LinkedList<Predicate>();
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.

这篇关于JPA条件查询中的条件where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:39