Sunday 12 January 2014


Using Annotations in Hibernate.

In order to be able to use the code provided in the tutorial you must have Oracle 11g installed on your local machine or at least have access to it somehow J. You must modify the properties
connection.url, connection.username, connection.password shown in step 3 to suit your database settings.

This will be the final folder structure for your application.


Step 1: Create a Java Application using eclipse. 
Click New, Java Project.



Give it a suitable name say “HibernateAnnotationPractise”. Click finish.


Step 2: Configure the build path.

You can download the jars from this link


Add the following jars to your build path.

To do that, right click you project, click Build Path, Configure Build Path.
Click on Libraries tab, Add External Jars and browse to the folder having all the jars


Step 3: Create the hibernate configuration xml file.
Right click on src folder, new, file. Give it the name hibernate.cfg.xml. click Finish


Add the following code to the 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>
              <!-- Setup the database connection -->
              <property name="connection.url">jdbc:oracle:thin:@localhost:1521:oracle</property>
              <property name="connection.username">SYSTEM</property>
              <property name="connection.password">Oracle123</property>
              <property name="connection.driver">oracle.jdbc.OracleDriver</property>
              <property name="connection.pool_size">1</property>
             
              <!-- SQL dialect -->
              <property name="dialect">org.hibernate.dialect.OracleDialect</property>
             
              <!-- Show sql statements to the  stdout -->
              <property name="show_sql">true</property>
             
              <!-- Configure the cache provider -->
              <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
             
              <!-- Generate the database DDL from hibernate configuration file -->
              <property name="hbm2ddl.auto">update</property>
              <!-- create = create the database and remove the existing schema if any -->
              <!-- update = update the database if the schema already exists. Throws exception if matching schema not found.  -->
              <!-- create-delete = create the database and drop the schema after the sessionFactory is closed. -->
              <!-- validate = validate the existing schema and no changes will be made to the database. -->
             
              <property name="hibernate.allow_sql_comments">true</property>
              <property name="hibernate.format_sql">false</property>
              <property name="hibernate.generate_statistics">true</property>
             
              <!-- Hibernate's automatic session context management -->
              <property name="current__session_context_class">thread</property>
             
              <!-- Classes to be mapped -->
              <mapping class="Employee"/>
       </session-factory>
</hibernate-configuration>

Note : I am using Oracle 11g. You will have to modify the connection.url, connection.username, connection.password properties as per your database configurations. You can use the code provided as a format for those properties.

Step 4: Add the file Employee.java, HibernateUtility.java and Client.java in your source package.

Employee.java

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;

@Entity
/*table will be created with name Employee. If you want to give some other name use the table annotation - @Table(name=”EMP1”)*/
public class Employee {

       @Id
       private int id;
       private String name;

       public int getId() {
              return id;
       }

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

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

}

HibernateUtility.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtility{
       private static final SessionFactory SESSION_FACTORY;
       static{
              SESSION_FACTORY = new AnnotationConfiguration().configure().buildSessionFactory();
       }
      
       public static SessionFactory getSessionFactory(){
              return SESSION_FACTORY;
       }
}

Client.Java

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class Client {
       public static void main(String[] args) {
              Employee e1 = new Employee();
              e1.setId(125);
              e1.setName("Satish");
               try {
                     Class.forName ("oracle.jdbc.OracleDriver");
              } catch (ClassNotFoundException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
               
              SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
              Session session = sessionFactory.openSession();
              Transaction transaction = session.beginTransaction();
             
             
session.persist(e1);
             
             
              transaction.commit();
              session.close();
       }
}

Run Client.java. Enjoy, your employee has been persisted to the database :)
In my next update I will post how to use NamedQuery and NamedNativeQuery annotations with hibernate.
All the best!!!