Hibernate Creating criteria instance

In this section you will learn about the creating of criteria instance in Hibernate.

Hibernate Creating criteria instance

Hibernate Creating criteria instance

In this section you will learn about the creating of criteria instance in Hibernate.

An instance of Criteria is created using the method createCriteria() of Session. Session is acted as a factory for instantiating the Criteria.

Example :

An example is being given below is a very simple example that describes the instantiation of Criteria. In this example I have shown a list of Worker by their workerId, firstname, lastname, cellphone. So to understand a complete example you will be required at first a table from where you will required to retrieve a stored data to as a search result here I have created a table named worker in MySQL. Next you will have to make a POJO/Persistent class to persist the objects here I have created Worker.java with the following properties workerId, firstname, lastname, cellphone and the constructor and getter/setter methods. Next you will be required a mapping file to map the persistent objects with the corresponding table fields here I have created a Worker.hbm.xml file, Next you will be required a configuration file using which Hibernate creates a connection pool and the required environment set up. Then using the Criteria query I have fetched the 5 maximum number of Worker list.

Worker Table

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`) 
)

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>

HibernateCriteriaInstanceExample.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.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateCriteriaInstanceExample 
{
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.setMaxResults(5);
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 :

Worker Table

When will you execute the java file HibernateCriteriaInstanceExample.java (RightClick -> Run As -> JavaApplication) an output will be displayed as :

Mar 15, 2012 6:36:06 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 15, 2012 6:36:06 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_ limit ?

Download Source Code