Hibernate 4 Simple Example

This section contains a simple Hibernate 4 example using Annotation with source code. The eclipse id and Apache Tomcat is used in this example.

Ads

Tutorials   
Hibernate envers custom revinfo table Hibernate 5 Envers Hibernate Envers get all revisions Hibernate Examples Hibernate 5 build SessionFactory Example Hibernate 5 SessionFactory Example Hibernate 5 Annotation Example How to download Hibernate 5.x? Hibernate 5 Features Hibernate 5 Tutorials Learning Hibernate ORM - Free Training/Tutorial videos of Hibernate ORM with Java How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate ORM 4.2.21.Final Released - Create CURD application in latest Hibernate Hibernate ORM 4.2.21 Tutorial - Learn Hibernate ORM Framework Hibernate Error: Failed to create sessionFactory object.java.lang.NoClassDefFoundError How to create Hibernate Project in Eclipse? Examples of Hibernate Criteria Query Hibernate ORM 4.3.6.Final released Hibernate ORM 4.2.14.Final released Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate association and join example Learn Hibernate programming with Examples Introduction to Hibernate Framework Hibernate Tutorial: Learn Hibernate with examples Hibernate 4.3 Hello World: Example Hibernate ORM 4.3.1.Final released How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate ORM 4.3.0.Final released Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment
Ads

Hibernate 4 Simple Example

This section contains a simple Hibernate 4 example using Annotation with source code. The eclipse id and Apache Tomcat is used in this example.

In Hibernate 4, buildSessionFactory( ) is deprecated. This example contains code which you can use in spite of buildSessionFactory ().

The project hierarchy is given below :

Here is the video instruction for developing and running the example in Eclipse:

The jar file used in this example is given below :

The database query used to create database is :

create table WORKER (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);

hibernate.cfg.xml

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

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/ankdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="worker.Worker" />

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

POJO class( Worker.java )

package worker;

import javax.persistence.*;

@Entity
@Table(name = "Worker")
public class Worker {
@Id
@GeneratedValue
@Column(name = "id")
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "salary")
private int salary;

public Worker() {
}

public Worker(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}


public String getFirstName() {
return firstName;
}

public void setFirstName(String first_name) {
this.firstName = first_name;
}

public String getLastName() {
return lastName;
}

public void setLastName(String last_name) {
this.lastName = last_name;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}
}

Application class( HandlingWorker.java )

package worker;

import java.util.List;
import java.util.Iterator; 

import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;


public class HandlingWorker {
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try{
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); 
factory = configuration.buildSessionFactory(serviceRegistry);
}catch (Throwable ex) { 
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex); 
}
HandlingWorker handle = new HandlingWorker();

/* Add few worker records in database */
Integer worker1 = handle.addWorker("Ram", "Prasad", 1000);
Integer worker2 = handle.addWorker("Rahul", "Das", 5000);
Integer worker3 = handle.addWorker("Steven", "Abraham", 10000);

/* List down all the workers */
handle.listWorkers();

/* Update worker's records */
handle.updateWorker(worker1, 5000);

/* Delete an worker from the database */
handle.deleteWorker(worker2);

/* List down new list of the workers */
handle.listWorkers();
}
/* Method to CREATE an worker in the database */
public Integer addWorker(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer workerID = null;
try{
tx = session.beginTransaction();
Worker worker = new Worker(fname, lname, salary);
workerID = (Integer) session.save(worker); 
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
return workerID;
}
/* Method to READ all the employees */
public void listWorkers( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Worker").list(); 
for (Iterator iterator = 
employees.iterator(); iterator.hasNext();){
Worker worker = (Worker) iterator.next(); 
System.out.print("First Name: " + worker.getFirstName()); 
System.out.print(" Last Name: " + worker.getLastName()); 
System.out.println(" Salary: " + worker.getSalary()); 
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
}
/* Method to UPDATE salary for an worker */
public void updateWorker(Integer WorkerID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Worker worker = 
(Worker)session.get(Worker.class, WorkerID); 
worker.setSalary( salary );
session.update(worker); 
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
}
/* Method to DELETE an worker from the records */
public void deleteWorker(Integer WorkerID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Worker worker = 
(Worker)session.get(Worker.class, WorkerID); 
session.delete(worker); 
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
}
}

OUTPUT

When you execute the above example you will get the following output in console :

Hibernate: insert into Worker (first_name, last_name, salary) values (?, ?, ?)
Hibernate: insert into Worker (first_name, last_name, salary) values (?, ?, ?)
Hibernate: insert into Worker (first_name, last_name, salary) values (?, ?, ?)
Hibernate: select worker0_.id as id0_, worker0_.first_name as first2_0_, worker0_.last_name 
as last3_0_, worker0_.salary as salary0_ from Worker worker0_
First Name: Ram Last Name: Prasad Salary: 1000
First Name: Rahul Last Name: Das Salary: 5000
First Name: Steven Last Name: Abraham Salary: 10000
Hibernate: select worker0_.id as id0_0_, worker0_.first_name as first2_0_0_, worker0_.last_name 
as last3_0_0_, worker0_.salary as salary0_0_ from Worker worker0_ where worker0_.id=?
Hibernate: update Worker set first_name=?, last_name=?, salary=? where id=?
Hibernate: select worker0_.id as id0_0_, worker0_.first_name as first2_0_0_, worker0_.last_name 
as last3_0_0_, worker0_.salary as salary0_0_ from Worker worker0_ where worker0_.id=?
Hibernate: delete from Worker where id=?
Hibernate: select worker0_.id as id0_, worker0_.first_name as first2_0_, worker0_.last_name 
as last3_0_, worker0_.salary as salary0_ from Worker worker0_
First Name: Ram Last Name: Prasad Salary: 5000
First Name: Steven Last Name: Abraham Salary: 10000

Download Source Code

Advertisements

Share on Google+Share on Google+

Hibernate 4 Simple Example

Posted on: February 1, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate 4 Simple Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:5
Neha
February 7, 2012
Create multiple tables

Hi, I want to write data into different tables for the same class using hibernate 4 annotations. For instance, I've a class Diagram. Now I want to create 3 tables using the sane class Diagram where primary key of one table is foreign key in the other table. create table DIAGRAM( diag_id INT NOT NULL auto_increment, name VARCHAR(20) default NULL, description VARCHAR(20) default NULL, PRIMARY KEY (diag_id)); create table ELEMENT( elem_id INT NOT NULL auto_increment, diag_id INT NOT NULL, style VARCHAR(20) default NULL, PRIMARY KEY (elem_id)); create table GEOMETRY( geom_id INT NOT NULL auto_increment, elem_id INT NOT NULL, xcoordinate VARCHAR(20) default NULL, ycoordinate VARCHAR(20) default NULL, PRIMARY KEY (geom_id));
Helmut Faasch
April 15, 2012
Bad Layout

Good content - but what a bad layout! You display lines of code which do not fit on one line. And to scroll to the left or right you first have to scroll down to the end of the page where the scroll bar is located. This ist one of the worst things to do in web page design
Mahesh V.Shet
September 29, 2012
Hibernate4

Cool One.....Happy this post helped me learn tip of Hibernate Iceberg....!!! Thanks.
Ian
June 15, 2013
Hibernate 4 Simple Example

Why in a Hibernate 4 Simple Example XML mapping use Hibernate 3 DTD ?
Bruno Tacca
October 30, 2013
Thank you!

Thank you very much!!!!! xD

Ads

 

Ads