Home > Blockchain >  Java : Is it possible to set paramters selectively?
Java : Is it possible to set paramters selectively?

Time:06-29

Using jdk1.8. I need to set a param in a jpa-native-query based on a boolean value. Something like (Please see the part where based on "addEmail"'s true/false value , trying to set/ignore "param3". em is the entityManager):

results = em.createNativeQuery(executionQuery)
                .setParameter("param1", val1)
                .setParameter("param2", val2)
                 if (addEmail){ .setParameter("param3", val3)}
                .setFirstResult(offset)
                .setMaxResults(max)
                .getResultList();

is there a way to do that? I was looking for some QueryOption. Not finding a good example

CodePudding user response:

Wouldn't this work for you?

var executionQuery = addEmail ? queryWithEmail : queryNoEmail;

var query = em.createNativeQuery(executionQuery)
                .setParameter("param1", val1)
                .setParameter("param2", val2)
                .setFirstResult(offset)
                .setMaxResults(max);

if (addEmail) query.setParameter("param3", val3);
   
return query.getResultList();
  • Related