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.

Student


//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
@Entity
@Table(name="Student")
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
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="STUDENT_ID")    
    public Long getId() {
        return id;
    }
    
    public void setId(Long id) {
        this.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) {
        this.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"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>


    <session-factory>

       <!-- 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="hbm2ddl.auto">validate</property>

        <!-- Mapping class.  --> 


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

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

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.

HibernateUtil


public class HibernateUtil {

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

static{
try{
//By default it will look for hibernate.cfg.xml in the class path
Configuration configuration = new Configuration();
   configuration.configure();
   serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
           configuration.getProperties()).build();
   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
getSessionFactory().close();
}

}


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");
  student.setAge(8);
  
  Long studentId = (Long)session.save(student);
  
  //Save another student
  Student student1 = new Student();
  student1.setName("E Bhatt");
  student1.setAge(3);
  Long studentId1 = (Long)session.save(student1);
  
  tx.commit();
  session.close();
  
  //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");
  
  tx.commit();
  session.close();  
  
  HibernateUtil.shutdown();
 }
}

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