Hibernate Criteria Associations

In this section you will learn about Criteria Query Association in Hibernate.

Hibernate Criteria Associations

Hibernate Criteria Associations

In this section you will learn about Criteria Query Association in Hibernate.

Association in Criteria Query may be done by using an additional createCriteria() method in the query, by using this method constraints can be defined upon the related entities. When an another createCriteria() method is used it returns a new instance of Criteria interface with the reference of specified collection. On the other way an association can also be done by using the createAlias() method, however, this method doesn't returns the instance of Criteria interface.

Example :

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

Table Employee

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'

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>

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>

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>

HibernateCriteriaAssociationExample.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 HibernateCriteriaAssociationExample 
{
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);
criteria.add(Restrictions.like("firstname", "Ankit"))
.createCriteria("employee").add(Restrictions.like("firstname", "Romesh"));
List ls = criteria.list();
Iterator it = ls.iterator();
System.out.println("WorkerId \t Worker_FirstName \t Worker_LastName \t Worker_CellPhone \t Employee_Id \t Employee_Firstname \t Employee_Lastname");
while(it.hasNext())
{
Worker worker = (Worker)it.next();
System.out.println(" "+worker.getWorkerId()+" \t\t "+worker.getFirstname()+" \t\t\t "+worker.getLastname()+" \t\t "+worker.getCellphone()+" \t\t "+worker.getEmployee().getEmpId()+" \t\t "+worker.getEmployee().getFirstname()+" \t\t "+ worker.getEmployee().getLastname());
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.close();
}
}
}

Output :

table worker

table employee

When you will execute the java file (RightClick ->RunAs -> JavaApplication) a query and output will be displayed on your console as :

Mar 20, 2012 12:58:46 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 20, 2012 12:58:46 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.workerId as workerId0_1_, this_.firstname as firstname0_1_, this_.lastname as lastname0_1_, this_.cellphone as cellphone0_1_, this_.employee_id as employee5_0_1_, employee1_.employee_id as employee1_1_0_, employee1_.firstname as firstname1_0_, employee1_.lastname as lastname1_0_ from worker this_ inner join employee employee1_ on this_.employee_id=employee1_.employee_id where this_.firstname like ? and employee1_.firstname like ?

Download Source Code