I'm trying to write a JPA query that has 3 conditional where statements. But I don't seem to get the syntax correct.
try {
Query findCustomerQuery = entityManager.createQuery("SELECT c FROM Customer c WHERE " +
"CASE " +
"WHEN :customerNumber is not null THEN (c.customerNumber = :customerNumber)" +
"WHEN :customerName is not null THEN (c.name = :customerName) " +
"WHEN :customerFirstname is not NULL THEN (c.firstName = :customerFirstname) ELSE (c.customerNumber = 0) END");
findCustomerQuery.setParameter("customerNumber",customerNumber);
findCustomerQuery.setParameter("customerName", customerName);
findCustomerQuery.setParameter("customerFirstname", customerFirstname);
return (Customer) findCustomerQuery.getSingleResult();
}finally {
entityManager.close();
}
It is convenient to use the JPA Criteria API for these cases.
Here is an example for your case:
// get a query builder
CriteriaBuilder builder = em.getCriteriaBuilder();
// build query for entity
CriteriaQuery<Customer> criteriaQuery = builder.createQuery( Customer.class );
// set FROM entity
Root<Customer> tags = criteriaQuery.from( Customer.class );
// get a basic predicate
Predicate p = builder.and();
// add WHERE conditions properly
if (customerNumber != null) {
Predicate conditionPredicate = builder.and(
builder.equal( tags.get("customerNumber"), customerNumber )
);
p = builder.and(p, conditionPredicate);
}
// do the same for customerName and customerFirstName
if (customerName != null) {
Predicate conditionPredicate = builder.and(
builder.equal( tags.get("customerName"), customerName )
);
p = builder.and(p, conditionPredicate);
}
if (customerFirstName != null) {
Predicate conditionPredicate = builder.and(
builder.equal( tags.get("customerFirstName"), customerFirstName )
);
p = builder.and(p, conditionPredicate);
}
// set predicate to query
criteriaQuery.where( p );
// call query and get results
TypedQuery<Customer> q = em.createQuery(criteriaQuery);
List<Customer> o = q.getResultList();
Here are more examples if you need
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.