Sunday, July 27, 2014

Hibernate Basic with Annotations

Before Java 5, Hibernate has XML way of configuring things. However with introduction of Annotations, the world has changed a lot. Many frameworks has adopted annotations as an alternative to XML. Hibernate has also adopted annotation. The XML way is still supported but annotation is the predominant way of working now. We will do the same example as we did in Hibernate Introduction using annotation.
Now let's write our domain class which is Student class.


//Entity annotation represents that it is an entity class and is
//mapped to a table in database. Table annotation tells about the 
//table name to which this entity is mapped
public class Student {
    //Id will correspond the primary key in the database
    private Long id;
    protected String name;
    //Id - Represents that it is a primary key column
    //GeneratedValue - How the key to be generated
    //column - Column to which this property is mapped
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    public void setId(Long id) { = id;
    //There is annotation here so by default it is mapped to
    //the column with name NAME. In annotation, the properties are
    //by default mapped. In XML mapping by default the columns
    //are not mapped.
    public String getName() {
        return name;
    public void setName(String name) { = name;

If you have done the Hibernate Introduction, you will realize that the mapping has been pulled in the class file itself in terms of annotations. The parallel can easily be drawn. Also now we do not need any mapping hbm.xml file. We still need the configuration XML, though the mapping will be done by referencing to class

hibernate.cfg.xml (Put it in the class path)

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


       <!-- Database connection settings --> 
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
        <!-- JDBC connection pool (use the built-in) --> 

        <property name="connection.pool_size">1</property>

        <!-- SQL dialect - This tells the SQL grammer to be used --> 

        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management --> 

        <property name="current_session_context_class">thread</property>

       <!-- Disable the second-level cache  --> 

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

        <!-- Log out all the sql that hibernate is issuing to datbase.

             This is very useful for debugging --> 

        <property name="show_sql">true</property>
        <!-- validates the table structure as per mapping definition. --> 

        <property name="">validate</property>

        <!-- Mapping class.  --> 

        <mapping class="com.oyejava.Student"/>


Let's write the Hibernate util class which is a utility class to make the Hibernate session factory. The Session factory at runtime contains all the configuration and mapping details. From Session factory we can get the Session, which is a lightweight object and helps us in interacting with the database. Session can be thought of as a Connection as in JDBC thought the Session may choose to not to open the connection to the database.


public class HibernateUtil {

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

//By default it will look for hibernate.cfg.xml in the class path
Configuration configuration = new Configuration();
   serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
   sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}catch(Throwable ex){
throw new ExceptionInInitializerError(ex);

public static SessionFactory getSessionFactory(){
return sessionFactory;

public static void shutdown(){
//Close caches and connection pool


Now in the application logic, in this case in the main method we can create a Student object and save it to the database.
public class HibernateBasic {

  public static void main(String[] args) {

   //Get the session from the Session factory

  Session session = HibernateUtil.getSessionFactory().openSession();  
  Transaction tx= session.beginTransaction();  
  //Save one student
  Student student = new Student();
  student.setName("Ishana Bhatt");
  Long studentId = (Long);
  //Save another student
  Student student1 = new Student();
  student1.setName("E Bhatt");
  Long studentId1 = (Long);
  //Start another unit of work
  session = HibernateUtil.getSessionFactory().openSession();
  tx= session.beginTransaction();  
  //Update Student after fetching it
  Student student2 = (Student)session.get(Student.class, studentId1);  
  student2.setName("Ekagra Bhatt");

Those who have done the hibernate in the XML way will note that the only difference the two has got is in terms of where the mapping is kept.  

Source Code at GitHub

More tutorials on Hibernate

No comments:

Post a Comment