Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate add Restriction ( equals ) only if the parameter is not null

Tags:

java

hibernate

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

like image 893
tania Avatar asked Aug 15 '12 13:08

tania


2 Answers

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();
like image 148
Aleksander Blomskøld Avatar answered Oct 13 '22 21:10

Aleksander Blomskøld


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.

like image 4
dimas Avatar answered Oct 13 '22 22:10

dimas