Make delicious recipes!


Working example in Hibernate


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>



Step 5: Person.hbm.xml (not used in this example)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Person" table="Person">
      <id name="id" type="int" column="id">
         <generator class="increment"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>


Step 6: Download ojdbc6.jar (or your database-specific jars)

Step 7: Download hibernate latest release or 4.2.6.Final (as used here)

Step 8: Put libs from #6 and #7 into a directory lib. It should look like:
lib/ojdbc6.jar
lib/hibernate-release-4.2.6.Final/lib
lib/hibernate-release-4.2.6.Final/lib/required
lib/hibernate-release-4.2.6.Final/lib/required/antlr-2.7.7.jar
lib/hibernate-release-4.2.6.Final/lib/required/dom4j-1.6.1.jar
lib/hibernate-release-4.2.6.Final/lib/required/hibernate-commons-annotations-4.0.2.Final.jar
lib/hibernate-release-4.2.6.Final/lib/required/hibernate-core-4.2.6.Final.jar
lib/hibernate-release-4.2.6.Final/lib/required/hibernate-jpa-2.0-api-1.0.1.Final.jar
lib/hibernate-release-4.2.6.Final/lib/required/javassist-3.15.0-GA.jar
lib/hibernate-release-4.2.6.Final/lib/required/jboss-logging-3.1.0.GA.jar
lib/hibernate-release-4.2.6.Final/lib/required/jboss-transaction-api_1.1_spec-1.0.1.Final.jar


Step 10: Capture the above into CLASSPATH by adding 'classpath' file to current directory:
.:lib/hibernate-release-4.2.6.Final/lib/required/antlr-2.7.7.jar:lib/hibernate-release-4.2.6.Final/lib/required/dom4j-1.6.1.jar:lib/hibernate-release-4.2.6.Final/lib/required/hibernate-commons-annotations-4.0.2.Final.jar:lib/hibernate-release-4.2.6.Final/lib/required/hibernate-core-4.2.6.Final.jar:lib/hibernate-release-4.2.6.Final/lib/required/hibernate-jpa-2.0-api-1.0.1.Final.jar:lib/hibernate-release-4.2.6.Final/lib/required/javassist-3.15.0-GA.jar:lib/hibernate-release-4.2.6.Final/lib/required/jboss-logging-3.1.0.GA.jar:lib/hibernate-release-4.2.6.Final/lib/required/jboss-transaction-api_1.1_spec-1.0.1.Final.jar:lib/ojdbc6.jar


Step 11: Finally, run the above setup by using following 'run' file as ./run:

echo "Compiling"
javac -cp `cat classpath` *.java

echo ""
echo ""
echo "Running"
java -cp `cat classpath` HibernateExample

echo ""
echo "Finished!"
echo ""




Output


The above example prints the below SQL when run.

/* 
   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=?








Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal