tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Hibernate > Criteria Queries > SQL Restriction

SQL Restriction 

The following example shows how to use Hibernate SQL Restriction. Refer first example for the configuration and mapping.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/criteria/CriteriaSQLRestrictionTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.hibernate.basic.criteria;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class CriteriaSQLRestrictionTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    System.out.println("Companies having atleast 65000 employees");
    getCompanies(65000);
    
    System.out.println("Companies having atleast 85000 employees");
    getCompanies(85000);
  }
  
  private static void getCompanies(int empCount) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    Criteria criteria = session.createCriteria(Company.class);
    criteria.add(Restrictions.sqlRestriction("{alias}.empcnt > " + empCount));
    List<Company> companies = criteria.list();    
    
    for (Company company : companies) {
      System.out.println(company);
    }
    
    session.getTransaction().commit();
    session.close();
  }

}
   

It gives the following output,
Companies having atleast 65000 employees
{ id = 4, name = IJK, employeeCount = 67890, 
	projectCount = 850, address1 = add1112, address2 = add2223 }
{ id = 5, name = ART, employeeCount = 67890, 
	projectCount = 850, address1 = add1112, address2 = add2223 }
{ id = 6, name = RNK, employeeCount = 98890, 
	projectCount = 8478, address1 = add1412, address2 = add27823 }
{ id = 7, name = AOQ, employeeCount = 97890, 
	projectCount = 4578, address1 = add17892, address2 = add2893 }

Companies having atleast 85000 employees
{ id = 6, name = RNK, employeeCount = 98890, 
	projectCount = 8478, address1 = add1412, address2 = add27823 }
{ id = 7, name = AOQ, employeeCount = 97890, 
	projectCount = 4578, address1 = add17892, address2 = add2893 }


                    Print

   



Books Recommendation

 
 
bl  br