how do i check if the parameter is null? Depending on the result i want to add or not to add the Restriction
if person.getLastName() == null i don't want to add the relevant restriction, how do i do this?
persons = session.createCriteria(PersonEntity.class).add(
Restrictions.eq("LastName", person.getLastName())).add(
Restrictions.eq("FirstName", person.getFirstName())).add(
Restrictions.eq("email", person.getUser().getEmail()))
.list();
Thanks, tania
You could just do it with a normal if in a method:
private void addRestrictionIfNotNull(Criteria criteria, String propertyName, Object value) {
if (value != null) {
criteria.add(Restrictions.eq(propertyName, value));
}
}
and then use it:
Criteria criteria = session.createCriteria(PersonEntity.class);
addRestrictionIfNotNull(critera, "LastName", person.getLastName());
addRestrictionIfNotNull(critera, "FirstName", person.getFirstName());
addRestrictionIfNotNull(critera, "email", person.getEmail());
persons = criteria.list();
You can use such complex restriction:
Restrictions.or(Restrictions.and(Restrictions.isNotNull("propName"), Restrictions.eq("propName", propValue)), Restrictions.isNull("propName"));
If I understand you correct it will do what you expect.
Result of the inner restriction Restrictions.eq("propName", propValue) will affect the result of the query only if specified property is not null.
PS. I know that it seems too obfuscated but for now I can't imagine another way to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With