JPQL check parameter is not null then execute query
I have some parameters that may be null or may not be empty.
I want to make a request with only parameters that are not null.
For example, I have:
String param1;
String param2;
And I want to do something like this:
If ( param1 != null && param2 != null ) {
Query q = em.createQuery("SELECT a FROM Advert where a.property = param1 and a.property2= param2);
}
if( param1 == null && param2 != null ) {
Query q = em.createQuery("SELECT a FROM Advert where a.property2= param2")
}
if( param1 != null && param2 == null ) {
Query q = em.createQuery("SELECT a FROM Advert where a.property= param1");
}
Is it possible to do this without using if statements but with a jpql query string? (because I have more than two parameters, and it is not so convenient to check so many cases)
+3
source to share
1 answer
You might have something like this:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Advert> query = criteriaBuilder.createQuery(Advert.class);
Root<Advert> advertRoot = query.from(Advert.class);
query.select(advertRoot);
List<Predicate> criteria = new ArrayList<Predicate>();
if(property != null){
ParameterExpression<String> p =
criteriaBuilder.parameter(String.class, "property");
criteria.add(criteriaBuilder.equal(advertRoot.get("property"), p));
}
if(property1 != null){
ParameterExpression<String> p =
criteriaBuilder.parameter(String.class, "property1");
criteria.add(criteriaBuilder.equal(advertRoot.get("property1"), p));
}
if (criteria.size() == 0) {
throw new RuntimeException("no criteria");
} else if (criteria.size() == 1) {
query.where(criteria.get(0));
} else {
query.where(criteriaBuilder.and(criteria
.toArray(new Predicate[0])));
}
TypedQuery<Advert> q = em.createQuery(query);
//set your query parameters here
if (property != null) { q.setParameter("property", property); }
if (property1 != null) { q.setParameter("property1", property1); }
List<Advert> resultList = q.getResultList();
+1
source to share