简体   繁体   中英

Or criteria - Hibernate

i have a hibernate class:

class student{
string name;
int roll;
}

while fetching records i have a requirement where i need to fetch records where name = "john" OR name = "paul", so basically i am trying to nget all records who have names as john or paul. I am not able to do the same. Please guide.

List students = sess.createCriteria(student.class)
    .add( Restrictions.eq("name", "John") )
    .add( Restrictions.eq("name", "Paul")) )
    .list();

This is the non working code.

Try:

List students = sess.createCriteria(student.class)
   .add( Restrictions.in("name", new String[] { "John", "Paul" } ) )
   .list();

PS. I recommend you using QueryDSL than Criteria API.

Something like this:

 Criteria crit = session.createCriteria(Student.class);
 Criterion name =  Restrictions.eq("name", "John") ;
 Criterion name2 = Restrictions.eq("name", "Paul"));
 LogicalExpression orExp = Restrictions.or(name,name2);
 crit.add(orExp);
 List<Student> results = crit.list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM