Home > Java > Simple JPA Application with Hibernate

Simple JPA Application with Hibernate


Now I am the newbie to JPA.I learn some thing about JPA. So I wanna share that with you all. So only I am here to do the same. This article deals with how to develop the simple JPA application using hibernate vendor support. Let’s get into that.


  • JDK 1.5 and above
  • Your favourite IDE.
  • HibernateJPA Library.
  • Mysqljdbc.jar

After create the Project we have to add above required libraries and jars into our library folder.

  • Table Creation.
  • Creation of  Persistence.xml
  • Creation of  Entity class
  • Creation of  Entity Manager class
  • Creation of  Test class.
1. Table Creation:

Create table named “Department”, which contains two columns “departmentId” and “departmentName” by executing the following script,

CREATE TABLE `Department` (
`departmentId` int(10) NOT NULL,
`departmentName` varchar(10) default NULL,
PRIMARY KEY  (`departmentId`))
2. Persistence.xml:

This persistence.xml file is act like configuration file for JPA.

<?xml version="1.0" encoding="UTF-8"?>

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

<persistence-unit name="JPASamplePU" transaction-type="RESOURCE_LOCAL">




<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>

<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpadb"/>

<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>

<property name="hibernate.hbm2ddl.auto" value="update"/>

<property name="hibernate.connection.username" value="root"/>

<property name="hibernate.connection.password" value="root"/>




Persistence-unit: used to represent the persistence unit.

Transaction-type: type of transaction

There are two type of transactions are avail.

Resource-local: Transactions have to be managed by developer locally.

JTA: Transactions are managed by application server.

Class: Represent the entity.

hbm2ddl.auto: used to perform the action in the database when the SessionFactory is created.

All the others are basic things.

3. Creation of Entity Class:

Entity class is used to represent the table in class format.

package com.bsj.entities;

import java.io.Serializable;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

@Entity//Represent the class entity class

@Table(name = "department")//Represents the table name



@NamedQuery(name = "Department.findAll", query = "SELECT d FROM Department d"), @NamedQuery(name = "Department.findByDepartmentId", query = "SELECT d FROM Department d WHERE d.departmentId = :departmentId"), @NamedQuery(name = "Department.findByDepartmentName", query = "SELECT d FROM Department d WHERE d.departmentName = :departmentName")


public class Department implements Serializable


private static final long serialVersionUID = 1L;


@Basic(optional = false)

@Column(name = "departmentId")

private Integer departmentId;

@Column(name = "departmentName")

private String departmentName;

public Department()



public Department(Integer departmentId)


this.departmentId = departmentId;


public Department(Integer departmentId, String DepartmentName)


this.departmentId = departmentId;

this.departmentName = departmentName;


//Getter setter method of variables

Annotation used in Entity Class:

@Entity – used to represent the class as Entity class. By using this annotation only we can make simple POJO class as Entity class.

@Table – used Represent the table name which the entity class points out.

@Id – Used to represent the primary key field.Only one primary key is allowed in the entity class.

@Column – used to represent the column details such as name, nullable etc.


There are two types of query is avail.
1. Static (Named) Queries: defined statically with the help of annotation (or XML) before the entity class.

A name of the Query  is usually given to the query definition so that other components in the same persistent unit can refer the query by the name.
2. Dynamic queries: are nothing but whose query strings are provided at run-time

4.Creation of Entity Manager Class:

The constructor has the Entity Manager Factory as argument and it allows us to create the Entity Manager.

The Entity Manager class is transaction scoped bean so we have to begin transaction before each action and commit transaction after each operation.

package com.bsj.entities;

import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Query;

public class DepartmentManager


private EntityManager em;

public DepartmentManager(EntityManagerFactory emf)


em = emf.createEntityManager();



* Method used to create department.

* @param department


public void createDepartment(Department department)


//Begin Transaction

System.out.println("Creation : ");


em.persist(department); //Persist entity in persistence context.

//Commit Transaction


System.out.println("Department Created SuccessFully");



* Method used to search department Name by id.

* @param id

* @return


public Department searchById(Integer id)


//Method used to find data

return em.find(Department.class, id);


public void updateUser(Department department)


System.out.println("Update : ");




System.out.println("Update successfully.");


public void removeUser(Department department)





System.out.println("Remove department successfully");


public List getAll()


Query query = em.createQuery("select a from Department a");

List list = query.getResultList();

return list;


public void close()





Methods used in Entity Manager:

Persist(entityObject)-Used to persist entity in the persistence context.
Find (Entityclass,value) – Find the datas regarding the input passed as argument.
merge(entityobject) : Update the database regarding to the passing details.
5.Creation of Test class:

We can get the entity manager factory by the  createEntityManagerFactory method of the class Persistence,
createEntityManagerFactory(persistence unit name);
This method has the persistence unit name as argument.
Call the entity manager methods by using the reference of entity manager.

package com.bsj.tester;

import com.bsj.entities.Department;

import com.bsj.entities.DepartmentManager;

import java.util.Iterator;

import java.util.List;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

public class TestJPA


private DepartmentManager departmentManager;

private EntityManagerFactory emf;


* Method to setup basic thing need for implementation like entiny manager

* factory,entity manager etc.

* @throws Exception


protected void setUp() throws Exception



* Create the entity manager factory with the help of persistence.

* @Param NameofPersistence unit form Persistence.xml


emf = Persistence.createEntityManagerFactory("JPASamplePU");


* create Departmanager

* @Param Entity Manager Factory


departmentManager = new DepartmentManager(emf);



* Method to close entity manager and entity manager factory.

* (i.e) Remove from the persistence context

* @throws Exception


protected void close() throws Exception






* Method for test the application.


public void test()



* Create the Entity by using constructor of Entity.


Department department = new Department(10, "Chemical");


System.out.println("Before Update :");

Department searchDepartment = departmentManager.searchById(50);

System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());



department = departmentManager.searchById(50);

System.out.println("After update.");

System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());

List list = departmentManager.getAll();

System.out.println("Number of Departments: " + list.size());

System.out.println("List of Departments : ");

Iterator iterator = list.iterator();

while (iterator.hasNext())


Department department3 = (Department) iterator.next();

System.out.println("Id : " + department3.getDepartmentId());

System.out.println("Name : " + department3.getDepartmentName());



public static void main(String args[])


System.out.println("Inside TestJPA main");

TestJPA testJPA = new TestJPA();







catch (Exception e)




System.out.println("End of TestJPA main");



Thats all folks.If you found this article was helpful to you,don’t forget to leave your valuable comments here.Happy coding….

  1. Matt
    July 6, 2011 at 10:22 am

    dude great tutorial, i know you’re struggling with the english and all but your code totally got me started right away. keep it up man

  2. November 30, 2012 at 4:37 am

    Grt dude..Kudos!!!

  3. varun
    December 11, 2012 at 5:51 pm

    thanks dude.. i just did a table creation from your tutorial.

  4. Aadav
    January 21, 2013 at 10:45 am

    nice really..!

  5. May 3, 2013 at 9:24 am

    buddy..can u list me the jars i need to put in???? else ur tutorial is fabulous

  6. Shwetha
    December 12, 2013 at 8:31 am

    Very helpful tutorial. Thanks a lot.:)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: