Hibernate Criteria Dynamic Association Fetching

In this tutorial you will learn about the dynamic association fetching in Criteria Query.

Hibernate Criteria Dynamic Association Fetching

Hibernate Criteria Dynamic Association Fetching

In this tutorial you will learn about the dynamic association fetching in Criteria Query.

In a Criteria Query a dynamic fetching operation can be done using the fields, JOIN, SELECT, of Enum FetchMode. Runtime association can be specified by the setFetchMode() method. The method setFetchMode() used with the fields JOIN, SELECT allows for joining in different ways.

Example

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, 
`employee_id` bigint(10) default NULL, 
PRIMARY KEY (`workerId`), 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC COMMENT='InnoDB free: 10240 kB' 

employee table

CREATE TABLE `employee` ( 
`employee_id` bigint(10) NOT NULL, 
`firstname` varchar(50) default NULL, 
`lastname` varchar(50) default NULL, 
PRIMARY KEY (`employee_id`), 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC COMMENT='InnoDB free: 10240 kB; 

Employee.java

package roseindia;

public class Employee
{
private int empId;
private String firstname;
private String lastname;

public Employee()
{

}


public Employee(String firstname, String lastname) {
super();
this.firstname = firstname;
this.lastname = lastname; 
}


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 int getEmpId() 
{
return empId;
}

public void setEmpId(int empId)
{
this.empId = empId;
}

}

Employee.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= "Employee" table="employee">
<id name= "empId" type="int" column="employee_id">
<generator class="native" />
</id>
<property name="firstname">
<column name="firstname"/>
</property>
<property name="lastname">
<column name="lastname"/>
</property>

</class>

</hibernate-mapping>

Worker.java

package roseindia;

public class Worker {
int workerId;
String firstname;
String lastname;
String cellphone;
Employee employee;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

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>
<many-to-one name="employee" class="roseindia.Employee" fetch="select">
<column name="employee_id" not-null="true"/>
</many-to-one>
</class>

</hibernate-mapping>

CriteriaDynamicAssociationFetchingExample.java

package roseindia;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
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 CriteriaDynamicAssociationFetchingExample 
{
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").addResource("roseindia/Employee.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)
.setFetchMode("wokeryee", FetchMode.JOIN)
.setFetchMode("employee", FetchMode.JOIN);
List ls = criteria.list();
Iterator it = ls.iterator();
System.out.println("WorkerId Worker_fName Worker_lName Worker_Phone Emp_Id Emp_fName Emp_lName");
while(it.hasNext())
{
Worker worker = (Worker)it.next();
System.out.println(worker.getWorkerId()+" \t "+worker.getFirstname()+" \t "+worker.getLastname()+" \t"+worker.getCellphone()+" "+worker.getEmployee().getEmpId()+" "+worker.getEmployee().getFirstname()+"\t"+ worker.getEmployee().getLastname());
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.close();
}
}
}

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>

Output :

worker table

employee table

When you will execute the java file CriteriaDynamicAssociationFetchingExample.java (RightClick ->Run As -> Java Application) the following output will be displayed on your console :

Download Source Code