Hibernate Narrowing Criteria Result Set

In this tutorial you will learn how to narrow the Criteria result set.

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

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 :

Download Source Code

Advertisements

Share on Google+Share on Google+

Hibernate Narrowing Criteria Result Set

Posted on: March 20, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate Narrowing Criteria Result Set  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads