Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to retrieve an object from database by primary key using Hibernate Framework ?.

Program to demonstrate how to retrieve an object from database by primary key using Hibernate Framework.

A simple POJO class (model), whose object we want to store and than retrieve back using primary key from database using Hibernate.

package com.hubberspot.hibernate.examples;

import javax.persistence.Entity;
import javax.persistence.Id;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 private int customerId;
 private String customerName;

 public int getUserId() {
  return customerId;
 public void setUserId(int userId) {
  this.customerId = userId;

 public String getUserName() {
  return customerName;
 public void setUserName(String userName) {
  this.customerName = userName;

Hibernate Configuration XML file

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">

 <!-- Drop and re-create the database schema on startup  -->
 <property name="">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />


A simple test class to save and than retrieve an object from database using the primary key.

package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();


  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.;

  // Committing the transaction in order to save. 
  // Closing the session

  // Pointing the customer to null in order to  
  // demonstrate how to fetch / retrieve the object 
  customer = null;

  // again opening a session from SessionFactory
  session = sessionFactory.openSession();

  // We use get method of the session for retrieving
  // the object from the database if we know the primary key
  // for which we want to retrieve. 
  // The get method takes in two arguments one is class object
  // for which we want to fetch record and second is the 
  // primary key.
  customer = (Customer) session.get(Customer.class, 1);
  // finally printing the retrieved customer name based on the 
  // primary key passed
  System.out.println("Customer Name retrived is : " + customer.getUserName());

Output of the program : 

© 2021 Learn Java by Examples Template by Hubberspot