tuntunsdsd dsd
tuntunsdsd dsd

Reputation: 11

putting hibernate or condition in criteria

Can you pls advise I need to put the or condition in hibernate criteria for one of the parameter that is..I am getting a parameter abcsystem now its value can be null also or it can not be null also but if it value is not null then set it value as it is to the parameter abcystem as it is , pls advise how to achieve this...

    Criteria criteria = session.createCriteria(ils.class);
    criteria.add(Restrictions.eq("Code", ok.getId()));
    //****criteria.add(Restrictions.eq("abcystem", ok.getabcSystem())); // ****criteria to be modified such that abc system can be null or //****we need to set the value of abc system whatever is coming in ok.getabcSystem() in the paremeter abcystem
    criteria.add(Restrictions.
    criteria.add(Restrictions.eq("tCode", ok.tCode()));

ment = (ils) criteria.uniqueResult();

Upvotes: 1

Views: 1832

Answers (2)

Radim Köhler
Radim Köhler

Reputation: 123861

If I read your requirement properly, what we have to do, is to evaluate the value of ok.getabcSystem() and:

  • use it if it is NOT null
  • do not use it if it is NULL

If this is what we need, the evaluation should not buble to the DB engine, we can do it in our server/app run-time:

Criteria criteria = session.createCriteria(ils.class);
criteria.add(Restrictions.eq("Code", ok.getId()));

if(ok.getabcSystem() != null) {
    criteria.add(Restrictions.eq("abcystem", ok.getabcSystem()))
}
...

Upvotes: 1

Mahesh
Mahesh

Reputation: 1081

Try this

  Criteria criteria = session.createCriteria(ils.class);
  criteria.add(Restrictions.eq("Code", ok.getId()));
  // OR condition 
  criteria.add( Restrictions.or(
        Restrictions.eq( "abcystem", ok.getabcSystem()),
        Restrictions.isNull("abcystem")
    ));
  criteria.add(Restrictions.eq("tCode", ok.tCode()));
 // your result here  ment = (ils) criteria.uniqueResult();

Upvotes: 0

Related Questions