To build a working Hibernate example, the following will be required:
Type
Used in this example
Description
Java
Version 1.6
Java environment to compile and run.
Database
Oracle
Java POJO
Person.java
A class which Hibernate will use to interact with the corresponding table.
Main Class
HibernateExample.java
A Java class to configure and run Hibernate.
Hibernate libraries
hibernate-release-4.2.6.Final
<Database>-specific library
ojdbc6.jar (for Oracle)
Each database has its own lib to interact with Hibernate.
hibernate.cfg.xml
Contains options to configure hibernate as a whole.
<POJO>.hbm.xml
Required only if not using the annotated-POJO version.
(Not used in this example).
Step 1: Create a table and a sequence in the database:
Create Table Person (
id Number(20) NOT NULL ,
first_name Varchar(64) ,
last_name Varchar(64) ,
salary Number(20) ,
PRIMARY KEY (id)
);
Create Sequence person_sequence
MinValue 1
MaxValue 20000
Start With 1
Increment By 1
Cache 100;
Select person_sequence.nextval from dual;
Step 2: Create a POJO class used by Hibernate to interface with the database:
import javax.persistence.*;
import static javax.persistence.GenerationType.*;
@Entity // Required annotation
@Table(name="Person") // can be omitted if table name is exactly same as Class name
@javax.persistence.SequenceGenerator(
name="P_SEQ",
sequenceName="person_sequence"
)
public class Person
{
@Id // Required annotation
@Column(name="ID") // can be omitted if column name is same as field-name
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="P_SEQ")
private int id;
private String firstName;
private String lastName;
private int salary;
public Person() {}
public Person(String fname, String lname, int salary)
{
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
// Getter - Setters
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;
}
}
Step 3: Create a main class to configure and run Hibernate:
import java.util.List;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateExample
{
private static SessionFactory factory;
public static void main(String[] args)
{
try
{
factory = new Configuration().configure().buildSessionFactory();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
HibernateExample example = new HibernateExample();
/* Add some records to the database */
Integer id1 = example.addRecord("Johny", "Travol", 10);
Integer id2 = example.addRecord("Kevin", "Becker", 20);
Integer id3 = example.addRecord("Bruce", "Almighty", 30);
/* Update a record */
example.updateRecord(id1, 50);
/* Delete */
example.deleteRecord(id3);
/* List the records */
example.listRecords();
}
/* CREATE a record in the database */
public Integer addRecord(String fname, String lname, int salary)
{
Session session = factory.openSession();
Transaction tx = null;
Integer id = null;
try
{
tx = session.beginTransaction();
Person p = new Person(fname, lname, salary);
id = (Integer) session.save(p);
tx.commit();
}
catch (Exception e)
{
if (tx!=null) tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
return id;
}
/* READ all the records */
public void listRecords()
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
List ppl = session.createQuery("FROM Person").list();
Iterator itr = ppl.iterator();
while (itr.hasNext())
{
Person p = (Person) itr.next();
System.out.println (
"Id: " + p.getId()
+ ", Name: " + p.getFirstName() + " " + p.getLastName()
+ ", Salary: " + p.getSalary()
);
}
tx.commit();
}
catch (Exception e)
{
if (tx!=null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* UPDATE a column in the DB */
public void updateRecord(Integer id, int salary )
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Person p = (Person)session.get(Person.class, id);
p.setSalary( salary );
session.update(p);
tx.commit();
}
catch (Exception e)
{
if (tx!=null) tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* Method to DELETE from the records */
public void deleteRecord(Integer id)
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Person p = (Person)session.get(Person.class, id);
session.delete(p);
tx.commit();
}
catch (HibernateException e)
{
if (tx!=null) tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
}
Step 4: Create hibernate.cfg.xml used to specify overall Hibernate options:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Type -->
<property name="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</property>
<property name="hibernate.connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<!-- Database Properties -->
<property name="hibernate.connection.url">
jdbc:oracle:thin:@//localhost:11521/XE
</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">manager</property>
<!-- Schema Validation -->
<property name="hbm2ddl.auto">validate</property>
<!-- Debugging and Formatting -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Required for annotations to work without Person.hbm.xml -->
<mapping class="Person" />
</session-factory>
</hibernate-configuration>
/*
Reads sequence values because of
the annotation javax.persistence.SequenceGenerator
*/
select
person_sequence.nextval
from
dual
/* SQL for insert operation */
insert into
Person
(firstName, lastName, salary, ID)
values
(?, ?, ?, ?)
/* SQL for read operation */
select
person0_.ID as ID1_0_0_,
person0_.firstName as firstNam3_0_0_,
person0_.lastName as lastName4_0_0_,
person0_.salary as salary5_0_0_,
from
Person person0_
where
person0_.ID=?
/* SQL for update operation */
update
Person
set
firstName=?,
lastName=?,
salary=?
where
ID=?
/* SQL for delete operation */
delete
from
Person
where
ID=?
Got a thought to share or found a bug in the code? We'd love to hear from you: