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

Viewed 33845

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

4 Answers

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.

Related