Disjunction Criteria
The following example shows how to use Hibernate Disjunction criteria.
Refer first example for the configuration and mapping.
package com.bethecoder.tutorials.hibernate.basic.criteria;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;
public class CriteriaDisjunctionRestrictionTest {
/**
* @param args
*/
public static void main ( String [] args ) {
Session session = HibernateUtil.getSessionFactory () .openSession () ;
session.beginTransaction () ;
Criteria criteria = session.createCriteria ( Company. class ) ;
Disjunction disjunction = Restrictions.disjunction () ;
disjunction.add ( Restrictions.eq ( "id" , new Integer ( 2 ))) ;
disjunction.add ( Restrictions.eq ( "id" , new Integer ( 4 ))) ;
disjunction.add ( Restrictions.eq ( "id" , new Integer ( 6 ))) ;
disjunction.add ( Restrictions.eq ( "id" , new Integer ( 8 ))) ;
criteria.add ( disjunction ) ;
List<Company> companies = criteria.list () ;
System.out.println ( "Selected row count : " + companies.size ()) ;
for ( Company company : companies ) {
System.out.println ( company ) ;
}
session.getTransaction () .commit () ;
session.close () ;
}
}
It gives the following output,
Selected row count : 4
{ id = 2, name = ABC, employeeCount = 23430,
projectCount = 160, address1 = add11, address2 = add22 }
{ id = 4, name = IJK, employeeCount = 67890,
projectCount = 850, address1 = add1112, address2 = add2223 }
{ id = 6, name = RNK, employeeCount = 98890,
projectCount = 8478, address1 = add1412, address2 = add27823 }
{ id = 8, name = BQO, employeeCount = 9778,
projectCount = 487, address1 = add1459, address2 = add2443 }