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) Customer.java, 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
@Entity 
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
 @Id
 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"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
 <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">
  org.hibernate.dialect.MySQL5Dialect
 </property>

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

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

  </session-factory>
</hibernate-configuration>


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();

  customer.setUserId(1);
  customer.setUserName("Jonty");  

  // 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().
    configure().buildSessionFactory();

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

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

  // Committing the transaction in order to save. 
  session.getTransaction().commit();
  // Closing the session
  session.close();

  // 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();
  session.beginTransaction();

  // 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 :