1
votes

I'm still trying to understand how the Restrictions.in("propName", ...) operator of the Hibernate Criteria object works.

Let's say I have an entity IceCream with nullable property flavour and I want to get all ice creams where flavour equals "chocolate", "banana" or null.

What is the correct way to do this using Hibernate criteria?

I tried this but it doesn't include rows where the icecream flavour is null in the result list:

String[] allowedFlavours = { "chocolate", "banana", null };
Criteria criteria = getSession().createCriteria(IceCream.class);
criteria.add(Restrictions.in("flavour", allowedFlavours));
return criteria.list();

Should I instead add a whole new criterion just to say "or flavour is null"? This just doesn't seem very efficient.

2

2 Answers

1
votes

Try this way

1>

 Criteria criteria = getSession().createCriteria(IceCream.class);
    criteria .add(Restrictions.disjunction().add(Restrictions.eq("flavour", "chocolate")).add(Restrictions.eq("flavour", "banana")).add(Restrictions.isNull("flavour")));

2>

String[] allowedFlavours = { "chocolate", "banana"};
Criteria criteria = getSession().createCriteria(IceCream.class);
criteria.add(Restrictions.disjunction().add(Restrictions.in("flavour", allowedFlavours)).add(Restrictions.isNull("flavour"));


return criteria.list();
0
votes

You can try the below code using disjunction()

disjunction : Group expressions together in a single disjunction (A or B or C...)

Criteria criteria = getSession().createCriteria(IceCream.class);
    criteria.add(Restrictions.disjunction()
    .add( Restrictions.isNull("flavour") )
    .add(Restrictions.in("flavour", new String[] { "chocolate", "banana" } ) );

Please add/remove brackets, format code appropriately as I have typed it manually.