Hibernate Narrowing Criteria Result Set
In this tutorial you will learn how to narrow the Criteria result set.
In Hibernate result set can be narrowed by using the restriction criteria. A custom restriction criteria is specified by implementing the org.hibernate.criterion.Criterion interface. To obtain the certain built-in Criterion types a class org.hibernate.criterion.Restrictions provides the factory method.
Example :
An example given below will demonstrates how can you narrow the result set. For creating this example at first I have created a table named worker in MySQL then created a POJO/Persistent class of which object is used to be persisted. Then created a mapping file to map the class property with the table, and a configuration file using which Hibernate creates a connection pool and required environment set up. Next created a main class where obtained a SessionFactory using ServiceRegistry then created a Session using SessionFactory. Next I have created an instance of Criteria and uses the Restrictions class for Narrowing the result set. Here I have used the static method like() of Restrictions class to retrieve the result by matching the firstname property of class.
Table worker
CREATE TABLE `worker` ( `workerId` int(10) NOT NULL auto_increment, `firstname` varchar(15) default NULL, `lastname` varchar(15) default NULL, `cellphone` varchar(11) default NULL, PRIMARY KEY (`workerId`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC COMMENT='InnoDB free: 10240 kB'
Worker.java
package roseindia; public class Worker { int workerId; String firstname; String lastname; String cellphone; public Worker() { } public Worker(String firstname, String lastname, String phone) { this.firstname = firstname; this.lastname = lastname; this.cellphone = phone; } public int getWorkerId() { return workerId; } public void setWorkerId(int workerId) { this.workerId = workerId; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getCellphone() { return cellphone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } }
Worker.hbm.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="roseindia"> <class name= "Worker" table="worker"> <id name= "workerId" type="int" column="workerId"> <generator class="native"/> </id> <property name="firstname"> <column name="firstname"/> </property> <property name="lastname"> <column name="lastname"/> </property> <property name="cellphone"> <column name="cellphone"/> </property> </class> </hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data </property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> </session-factory> </hibernate-configuration>
HibernateNarrowingCriteriaResultSet.java
package roseindia; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateNarrowingCriteriaResultSet { private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; public static void main(String args[]) { Session session = null; try { try { Configuration cfg= new Configuration().addResource("roseindia/Worker.hbm.xml"); cfg.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); sessionFactory = cfg.buildSessionFactory(serviceRegistry); } catch(Throwable th) { System.err.println("Failed to create sessionFactory object." + th); throw new ExceptionInInitializerError(th); } session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(Worker.class); criteria.add(Restrictions.like("firstname", "Ankit")); List<Worker> ls = criteria.list(); Iterator<Worker> it = ls.iterator(); System.out.println("WorkerId \t FirstName \t LastName \t CellPhone"); while(it.hasNext()) { Worker worker = it.next(); System.out.println(worker.getWorkerId()+"\t\t "+worker.getFirstname()+" \t "+worker.getLastname()+" \t "+worker.getCellphone()); } } catch(Exception e) { System.out.println(e.getMessage()); } finally { session.close(); } } }
Output :
Table worker
When you will execute the java file HibernateNarrowingCriteriaResultSet.java (RightClick -> RunAs -> JavaApplication) the following Query will be generated by the Hibernate :
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions) Mar 16, 2012 3:25:41 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init> INFO: HHH000397: Using ASTQueryTranslatorFactory Hibernate: select this_.workerId as workerId0_0_, this_.firstname as firstname0_0_, this_.lastname as lastname0_0_, this_.cellphone as cellphone0_0_ from worker this_ where this_.firstname like ?
And the narrowed result set will be displayed to you as :