hibernate
Retrieve record in Hibernate with Criteria
In this example we shall show you how to retrieve a record in Hibernate with Criteria. To retrieve a record in Hibernate with Criteria we have performed the following steps:
Employeeclass is the class whose objects will be inserted to the database.- In
RetrieveRecordInHibernateWithCriteriawe use the Hibernate API to make the interface with the database. - We create a new
Configuration, that allows the application to specify properties and mapping documents to be used when creating aSessionFactory. Usually an application will create a singleConfiguration, build a single instance ofSessionFactoryand then instantiateSessionsin threads servicing client requests. Usingconfigure()API method we use the mappings and properties specified in an application resource namedhibernate.cfg.xml. Then, withbuildSessionFactory()we instantiate a newSessionFactory, using the properties and mappings in this configuration. - Use the
getCurrentSession()API method to obtain the current session. - Use the
beginTransaction()API method to begin a unit of work and return the associatedTransactionobject. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction. - Create new
Employeeobjects and usesave(Object object)API method ofSessionto persist the given transient instances to the database. - Use
getTransaction()API method ofSessionandcommit()API method of Transaction to commit theTransaction. - Use the
beginTransaction()API method again. Now create a newCriteria, using thecreateCriteria(Class persistentClass)API method ofSessionfor the givenEmployeeclass. - Use
add(Criterion criterion)to addRestrictionsto constrain the results to be retrieved. - Use methods of
Restrictionsto constraint the results. For example,eq(String propertyName, Object value)applies an “equal” constraint to the named property. - Use the
uniqueResult()API method ofCriteriato get the single instance that matches the query. - Use again
getTransaction()API method ofSessionandcommit()API method of Transaction to commit theTransaction.
In the code snippets that follow, you can see the Employee class and the RetrieveRecordInHibernateWithCriteria Class that applies all above steps. You can also take a look at the hibernate.cfg.xml file, that holds all configuration for Hibernate, such as JDBC connection settings, and employee.hbm.xml file that holds the mapping configuration between the Employee class and the Employee table.
package com.javacodegeeks.snippets.enterprise;
import java.util.Date;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
public class RetrieveRecordInHibernateWithCriteria {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
for (int i = 0; i < 100; i++) {
Employee employee = new Employee();
employee.setName("employe_"+i);
employee.setSurname("surname_"+i);
employee.setTitle("Engineer_"+i);
employee.setCreated(new Date());
session.save(employee);
}
session.getTransaction().commit();
}
catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session = sessionFactory.getCurrentSession();
long employeeId = 25;
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.eq("id", employeeId));
Employee employee = (Employee) criteria.uniqueResult();
if (employee!=null) {
System.out.println("Employee found:");
System.out.println(employee.getId() + " - " + employee.getName());
}
session.getTransaction().commit();
}
catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
}
package com.javacodegeeks.snippets.enterprise;
import java.util.Date;
public class Employee {
private Long id;
private String name;
private String surname;
private String title;
private Date created;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/companydb</property>
<property name="connection.username">jcg</property>
<property name="connection.password">jcg</property>
<!-- JDBC connection pool, use Hibernate internal connection pool -->
<property name="connection.pool_size">5</property>
<!-- Defines the SQL dialect used in Hiberante's application -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Display and format all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Mapping to hibernate mapping files -->
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javacodegeeks.snippets.enterprise.Employee" table="employee">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" not-null="true" length="50" />
<property name="surname" not-null="true" length="50" />
<property name="title" length="50" />
<property name="created" type="timestamp" />
</class>
</hibernate-mapping>
Output:
Employee found:
25 - employe_24
This was an example of how to retrieve a record in Hibernate with Criteria.

