tania
tania

Reputation: 1086

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

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

Upvotes: 6

Views: 34829

Answers (4)

Madushan Perera
Madushan Perera

Reputation: 2598

If your last_name column is always not null in the table, you can try something like below :

String lastName = .. ;

.add(Restrictions.sqlRestriction(lastName != null ? "this_.last_name = "+ lastName : "this_.last_name is not null "))

Here the last_name will be your table column name.

Upvotes: 0

Priyanka Gupta
Priyanka Gupta

Reputation: 1740

So, u can do like this,

session = sessionFactory.getCurrentSession();
Criteria crit = session.createCriteria(PersonEntity.class).add(
                Restrictions.eq("FirstName", person.getFirstName())).add(
                Restrictions.eq("email", person.getUser().getEmail()));
if(person.getLastName()!=null){
crit.add(Restrictions.eq("LastName", person.getLastName()));
}
person=(PersonVO)crit.list();

Upvotes: 0

Aleksander Blomskøld
Aleksander Blomskøld

Reputation: 18552

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();

Upvotes: 12

dimas
dimas

Reputation: 6073

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.

Upvotes: 4

Related Questions