user2455158
user2455158

Reputation: 97

Optional or Null Parameters JPA

I am new to Eclipselink JPA. I have a set of complex search queries with a number of search parameters, some of the parameters are optional. Is there a way to specify optional parameters in named query? Is the below approach an efficient way to do? select o from Product o WHERE :value is null or o.category = :value'

Upvotes: 1

Views: 4204

Answers (1)

DannyMo
DannyMo

Reputation: 11984

Your approach would probably work, but I normally use the Criteria API in similar situations. For example, you could conditionally add predicates to your criteria query if the parameters are provided:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> e = cq.from(Product.class);

List<Predicate> predicates = new ArrayList<Predicate>();
if (categoryValue != null)
  predicates.add(cb.equal(e.get("category"), categoryValue));
if (someOtherValue != null)
  predicates.add(cb.equal(e.get("someField"), someOtherValue));

// AND all of the predicates together:
if (!predicates.isEmpty())
  cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));

List<Product> products = em.createQuery(cq).getResultList();

This is kind of an ugly example, but the CriteriaBuilder is very powerful once you become familiar with the API.

Upvotes: 4

Related Questions