I have this method:
public List<User> getReport(String name, int age, String sName, Date bd,
String address, String msg2, int first, int pageSize) {
List<User> result = new ArrayList<>();
result = em.createQuery("from User u, User.class)
.setFirstResult(first)
.setMaxResults(pageSize)
.getResultList();
return result;
}
Now, this method return all data. I need sett dynamicly parameters. I can make this:
result = em.createQuery("from User u WHERE u.age = :age", User.class)
.setParameter("age", age)
.setFirstResult(first)
.setMaxResults(pageSize)
.getResultList();
But if my age is null - I dont get result. And with another fields.
I need somethign like:
if(age != null){
em.createQuery("from User u WHERE u.age = :age", User.class)
.setParameter("age", age)
}
if(name!= null){
em.createQuery("from User u WHERE u.age = :age AND u.name= :name", User.class)
.setParameter("age", age)
}
I can format string query like:
String query = "from User u WHER";
and them concate this string
if(age != null){
query = query +"u.age = :age";
em.createQuery("from User u WHERE u.age = :age", User.class)
.setParameter("age", age)
}
But I thing it is bad practice.