Home » Enterprise Java » hibernate » Retrieve object by Id in Hibernate

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Retrieve object by Id in Hibernate

With this example we are going to demonstrate how to retrieve an object by id in Hibernate. In short, to retrieve an object by id in Hibernate  we have set the example below:

  • Employee class is the class whose objects will be inserted to the database.
  • In RetrieveObjectByIdInHibernate we 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 a SessionFactory. Usually an application will create a single Configuration, build a single instance of SessionFactory and then instantiate Sessions in threads servicing client requests. Using configure() API method we use the mappings and properties specified in an application resource named hibernate.cfg.xml.  Then, with buildSessionFactory() we instantiate a new SessionFactory, 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 associated Transaction object. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction.
  • Create a new Employee object and use save(Object object) API method of Session to persist the given transient instances to the database.
  • Use getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction.
  • Use the beginTransaction() API method again. Now create a new Query, using the createQuery(String queryString) API method of Session, with a given query.
  • Use get(Class clazz, Serializable id) API method of Session to get the persistent instance of the given entity class with the given identifier.
  • Use again getTransaction() API method of Session and commit() API method of Transaction to commit the Transaction.

In the code snippets that follow, you can see the Employee class and the RetrieveObjectByIdInHibernate 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.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class RetrieveObjectByIdInHibernate {
	
public static void main(String[] args) {
		
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		
		Session session = sessionFactory.getCurrentSession();

		Employee employee = new Employee();
		employee.setName("employee_name");
		employee.setSurname("employee_surname");
		employee.setTitle("employee_title");
		employee.setCreated(new Date());
		
		try {
			session.beginTransaction();
			session.save(employee);
			session.getTransaction().commit();
			System.out.println("Employee saved with ID: " + employee.getId());
		}
		catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		
		long id = employee.getId();
		
		session = sessionFactory.getCurrentSession();
		
		try {
			session.beginTransaction();
			
			Employee dbEmployee = (Employee) session.get(Employee.class, id);
			System.out.println(dbEmployee.getId() + " - " + dbEmployee.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>
CREATE TABLE `companydb`.`employee` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `surname` VARCHAR(45) NOT NULL,
  `title` VARCHAR(45) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);

Output:

Hibernate: 
    insert 
    into

  employee

  (name, surname, title, created) 
    values

  (?, ?, ?, ?)
Employee saved with ID: 65
Hibernate: 
    select

  employee0_.id as id0_0_,

  employee0_.name as name0_0_,

  employee0_.surname as surname0_0_,

  employee0_.title as title0_0_,

  employee0_.created as created0_0_ 
    from

  employee employee0_ 
    where

  employee0_.id=?
65 - employee_name

 
This was an example of how to retrieve an object by id in Hibernate.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of