Tuesday, July 22, 2014

Hibernate basic configuration and a simple project

Having worked on the back-end for a long time, It was time for me to re-visit some of the back-end stuff and revise the work done. While I was doing that I decided to jot down things for further use :).

Spring-Hibernate are one of the best frameworks currently used for Web-services development. We will start by getting to know Hibernate first, followed by Spring and a complete integration in the later posts.

In the early days of Java Programming developers accessed databases/performed operations using the built in classes provided by the java.sql.* package. Problems with this was we had a lot of connections that were not Freed up. We then had Connection Pools which solved the problem of connection management, but still there was a lot of code for sql queries/result set parsing,etc. After which we had Hibernate into picture.

With Hibernate it became easy to perform database operations.Hibernates manages the state  of objects and developers need not worry on when to read/write from a database. Hibernate is an opensource, light weight ORM -object Relational Mapping tool

To describe in short of where hibernate comes into picture, you can refer the below diagram:



The main elements of Hibernate Architecture include: Session, SessionFactory,Tranaction,ConnectionProvider,Transaction,TransactionFactory

To create a Hibernate Project we need to follow some basic steps:
1. We will create the Persistent class
2. Create a mapping file for the Persistent
3. Create the configuration file
4. Create a class which will retrieve/store the Persistent Objects

The jar's required for hibernate would be: cglib,log4j,slf4j,commons,dom4j,etc.
A complete set can be downloaded at: download all hibernate jars

We will begin by creating a simple Persistent class say Employee:

Employee.java
 package com.sample.models;   
 public class Employee {   
 private int id;   
 private String firstName,lastName;   
 public int getId() {   
   return id;   
 }   
 public void setId(int id) {   
   this.id = id;   
 }   
 public String getFirstName() {   
   return firstName;   
 }   
 public void setFirstName(String firstName) {   
   this.firstName = firstName;   
 }   
 public String getLastName() {   
   return lastName;   
 }   
 public void setLastName(String lastName) {   
   this.lastName = lastName;   
 }   
 }   
Now, create the mapping file: employee.hbm.xml
 <?xml version='1.0' encoding='UTF-8'?>   
 <!DOCTYPE hibernate-mapping PUBLIC   
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
  <hibernate-mapping>   
  <class name="com.sample.models.Employee" table="Employee">   
   <id name="id">   
    <generator class="assigned"></generator>   
   </id>   
   <property name="firstName"></property>   
   <property name="lastName"></property>   
  </class>   
  </hibernate-mapping>   
Create configuration file hibernate.cfg.xml
 <?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>   
     <property name="hbm2ddl.auto">update</property>   
     <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>   
     <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>   
     <property name="connection.username">system</property>   
     <property name="connection.password">oracle</property>   
     <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>   
   <mapping resource="employee.hbm.xml"/>   
   </session-factory>   
 </hibernate-configuration>   
For connecting your application with the database, you will need to specify an SQL dialect. All the dialects are defined in the org.hibernate.dialect package.

For postgress you can use: org.hibernate.dialect.PostgreSQLDialect
Create a class which will save/ get these objects:
 package com.samples.service;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.hibernate.cfg.Configuration;  
 public class DataManager {  
 public static void main(String[] args) {  
   //creating configuration object  
   Configuration cfg=new Configuration();  
   cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
   //creating seession factory object  
   SessionFactory factory=cfg.buildSessionFactory();  
   //creating session object  
   Session session=factory.openSession();  
   //creating transaction object  
   Transaction t=session.beginTransaction();  
   Employee e1=new Employee();  
   e1.setId(111);  
   e1.setFirstName("snehal");  
   e1.setLastName("vetal");  
   session.persist(e1);//persisting the object  
   t.commit();//transaction is commited  
   session.close();  
   System.out.println("successfully saved");  
 }  
 }  
If you run the above class, you should be able to save the Employee object and retrieve data.

This was a very simple example to just start using hibernate. There are many things to explore like inheritance mapping,collection mapping, association mapping, transaction mapping, HQL etc.
If I get free time, will keep updated on cleaner ways to integrate Spring and Hibernate and any tips.
You should be able to find a lot of resources on the web for both and once the base architecture for a app is ready, its pretty easier to implement new Persistence Objects and maintain them, webservices are easier to code faster with Spring.

Let's see a few more examples in the next posts.






No comments:

Post a Comment