Tech I Enjoy Logo

Custom Search




  Home >> Spring Framework


Spring Hibernate DAO support example with a very easy to
setup and run.

In this example I shall be using a single JSP file to
render UI, a Java Bean helper class to call a service
(this service is also a POJO bean). This service will
be having a data access object instance variable, which
will actually be injected into at runtime by the Spring
Framework related configuration. In order to make the
DAO integrating with service bean to be loosely coupled
here I will be using an DAO interface and the actual
implementation will be injected to service at runtime.

This DAO will be having this example specific method definitions, and is defined as an interface. By using Spring's Hibernate DAO Support, I will be trying to integrate/use inbuilt HibernateTemplate from Spring Framework wrapper over Hibernate Session and thus making available most of the method from Hibernate's Session object, such as save, saveOrUpdate, update, get, load, delete and many more. This very example that I am talking about here in this note is a very simple, not so close to any real world application, but I think is having enough material to discuss one of the way is possible to use DAO design pattern along with Hibernate and Spring DAO support. In this example there is a Book and a Category domain classes, those are mapped as one to one type mapping and each class is mapped to one table in this example database. So we have Book and Category objects are persisted in book and category tables in MySQL database. Book has a private instance variable for associating with Category in a one to one mapping type using Hibernate as ORM. Book.java
package example.iqtf.domain;

import java.io.Serializable;

public class Book implements Serializable {
  private String bookId;
  private String bookTitle;
  private Category category;
  public String getBookId() {
	return bookId;
  }
  public void setBookId(String bookId) {
	this.bookId = bookId;
  }
  public String getBookTitle() {
	return bookTitle;
  }
  public void setBookTitle(String bookTitle) {
	this.bookTitle = bookTitle;
  }
  public Category getCategory() {
	return category;
  }
  public void setCategory(Category category) {
	this.category = category;
  }
}
Category.java
package example.iqtf.domain;

import java.io.Serializable;

public class Category implements Serializable{
  private String categoryId;
  private String categoryTitle;
  public String getCategoryId() {
	return categoryId;
  }
  public void setCategoryId(String categoryId) {
	this.categoryId = categoryId;
  }
  public String getCategoryTitle() {
	return categoryTitle;
  }
  public void setCategoryTitle(String categoryTitle) {
	this.categoryTitle = categoryTitle;
  }
}
Corresponding tables are created using following SQL scripts using MySQL as database:
MySQL database table creation script:

	create table category (category_id varchar(4) not null,
	                       category_title varchar(50) not null,
	                       primary key(category_id));

	create table book (book_id varchar(4) not null,
	                   book_name varchar(50) not null,
	                   primary key (book_id));

Various parts of this example as shown in this following deployment diagram : example Deployment Diagram From this diagram it seems clear that there is a JSP file book.jsp, which is calling a helper bean, and this helper bean gets an instance of the service bean from Spring's Application Context. This service bean is calling a specific implementation of DAO interface, which is BookDAO, in this example. Following class diagram depicts the way various class files such as ApplicationDAOSupport (extending Spring's HibernateDAOSupport), BookDAO (implementation of the DAO interface). example DAO class Diagram so the service class , BookService is going to use instance of BookDAO being injected to service (BookService). JSP Helper bean is going to create Spring's Application Context and will seek BookService and call appropriate method. I have tried this example and it is performing as i expected it to perform, in a specific software runtime environment. I have tested this example using following software environment: -> JDK 1.5 -> JBoss 4.0.4 GA -> Eclipse 3.2 -> Hibernate 3.2 -> Spring Framework 1.2.8 -> MySQL 5.0 One may have to configure Data source for connecting to a database instance, in this example I have created a XML file "mysql-ds.xml" mysql-ds.xml
<?xml version="1.0" encoding="UTF-8"?>
<data sources>
   <local-tx-datasource>
      <jndi-name>MysqlDS</jndi-name>
      <connection-url>jdbc:mysql://localhost:3306/test</connection-url>
      <driver-class>org.gjt.mm.mysql.Driver</driver-class>
      <user-name>test</user-name>
      <password>test</password>
      <min-pool-size>10</min-pool-size>
      <max-pool-size>20</max-pool-size>
      <idle-timeout-minutes>0</idle-timeout-minutes>
      <track-statements/>
      <metadata>
         <type-mapping>mySQL</type-mapping>
      </metadata>
   </local-tx-datasource>
</data sources>
All the configuration parameters shown above are having values those I think are okay for my example, need not be understood as the best way to do. So one may have to explore more options if required. So in this example, data source name is "MysqlDS" and is connected to test database with user name as "test" and password as "test". Once this data source configuration is working, then I started creating all the source files such as shown as follows: src (example.iqtf.dao) ------------------ ApplicationDaoSupport.java
package example.iqtf.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ApplicationDaoSupport extends HibernateDaoSupport {
    public Object save(Object obj) {
      Object obj1 = null;
      Transaction trans = getSession().beginTransaction();
      trans.begin();
      try {
        obj1 =  getHibernateTemplate().save(obj);
        trans.commit();
      } catch (HibernateException he) {
        trans.rollback();
      }
      return obj1;
    }
    public Object get(Class cls, Serializable str) {
      return getHibernateTemplate().get(cls, str);
    }
    public List loadAll(Class cls) {
    	List lst = null;
    	Transaction trans = getSession().beginTransaction();
    	trans.begin();
    	lst = getHibernateTemplate().find("from Book");
    	trans.commit();
    	return lst;
    }
  }
As you might have noted that, this ApplicationDaoSupport class is having most of the comon methods like save, delete, saveOrUpdate loadAll, get etc., are implemented. These methods will have the HibernateTemplate from the super class HibernateDAOSupport from SpringFramework's DAO Support api. DAO.java
package example.iqtf.dao;

import java.util.List;

import example.iqtf.domain.Book;
import example.iqtf.domain.Category;
import example.iqtf.exception.ApplicationException;

public interface DAO {
  public Book saveBook(Book bk) throws ApplicationException;
  public Category findCategory(String ctgName) throws ApplicationException;
  public List listAllBooks() throws ApplicationException;
}
This DAO interface will have most of the methods specific to this example, as shown above. Now we need to look at the implementation class for this DAO interface, BookDAO.java
package example.iqtf.dao;

import java.util.List;

import example.iqtf.domain.Book;
import example.iqtf.domain.Category;
import example.iqtf.exception.ApplicationException;

public class BookDAO extends ApplicationDaoSupport
                     implements DAO {

  public Book saveBook(Book bk) throws ApplicationException {
    System.out.println("storing bk:"+bk);
    save(bk);
    return bk;
  }

  public Category findCategory(String ctgName)
                                throws ApplicationException {

    return (Category) get(Category.class,ctgName);
  }

  public List listAllBooks() throws ApplicationException {
    return loadAll(Book.class);
  }
}
So this example specific DAO, i.e, BookDAO extends ApplicationDaoSupport and implements DAO methods. As shown in the deployment/component diagram above, BookService will have the DAO, injected into the service. BookService.java
package example.iqtf.service;

import java.util.List;

import example.iqtf.dao.DAO;
import example.iqtf.domain.Book;
import example.iqtf.domain.Category;
import example.iqtf.exception.ApplicationException;

public class BookService {
    private DAO bookDao = null;
  public DAO getBookDao() {
    return bookDao;
  }

  public void setBookDao(DAO bookDao) {
    this.bookDao = bookDao;
  }

  public Book registerBook(Book bk, String ctgName,
                                    String ctgTitle)
                       throws ApplicationException {
    Category ctg = bookDao.findCategory(ctgName);
    if(ctg == null) {
      ctg = new Category();
      ctg.setCategoryId(ctgName);
      ctg.setCategoryTitle(ctgTitle);
    }
    bk.setCategory(ctg);
    return bookDao.saveBook(bk);
  }
  public List listBooks() throws ApplicationException {
    return bookDao.listAllBooks();
  }
}
Following is the helper class that uses the BookService: UserInterfaceHelper.java
package example.iqtf.helper;

import java.util.Iterator;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import example.iqtf.domain.Book;
import example.iqtf.domain.Category;
import example.iqtf.exception.ApplicationException;
import example.iqtf.service.BookService;

public class UserInterfaceHelper {
	static ClassPathXmlApplicationContext ctx = null;
  static {
  ctx
  = new ClassPathXmlApplicationContext("spring-config/applicationContext.xml");
  }
  public Book storeBook(Book bk, String ctgName, String ctgTitle)
                                     throws ApplicationException {
    Book bkTmp = null;
    try {
      bkTmp = ((BookService) ctx.getBean("BookService"))
                                         .registerBook(bk, ctgName, ctgTitle);
    } catch (ApplicationException ex) {
     //Log exception;
      throw ex;
    }
   return bkTmp;
  }

  public String[][] listBooks() throws ApplicationException {
   List lst = ((BookService) ctx.getBean("BookService")).listBooks();
   Iterator itr = lst.iterator();
   String[][] str = new String[lst.size()][lst.size()];
   int i=0;
   while(itr.hasNext()) {
     Book bk = (Book)itr.next();
     if(bk != null) {
       Category ct = bk.getCategory();
       if(ct != null) {
        str[i][0] = bk.getBookId();
        str[i][1] = bk.getBookTitle();
        str[i][2] = ct.getCategoryId();
        str[i][3] = ct.getCategoryTitle();
        i++;
       }
     }
   }

  return str;
 }
}
This helper bean class uses Spring's ClassPath XML Application context and the applicationContext.xml file to create the bean factory, and thus obtaining the BookService as bean. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="myDataSource"
      class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/MysqlDS"/>
</bean>

<bean id="mySessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>
  /WEB-INF/config/hibernate-config/BookCategory.hbm.xml
</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
    org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>

</bean>
<bean id="BookDAO" class="example.iqtf.dao.BookDAO">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id="BookService" class="example.iqtf.service.BookService">
<property name="bookDao" ref="BookDAO"/>
</bean>
</beans>
BookCategory.hbm.xml file has the related mapping of Book and Category POJO in form of one to one mapping, as shown below:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="example.iqtf.domain">
<class name="Book" table="book">
<id name="bookId" access="property" column="book_id"/>
<property name="bookTitle" access="property" column="book_name"/>
<one-to-one name="category" class="Category" cascade="all"/>
</class>

<class name="Category" table="category" >
<id name="categoryId" access="property" column="category_id"/>
<property name="categoryTitle" access="property"
                               column="category_title"/>
</class>
</hibernate-mapping>
For the UI tier JSP file, I have used a very simple Screen with four text fields for user input and a submit button. On submission of the form tag, same JSP file is called and this file checks for the request parameters and calls the helper bean to move data from UI to database layer, and finally saves/persists values to respective tables. If anything missed out , please let me know at techienjoy at yahoo . com
Spring Framework Singleton Example :
Spring Framework Singleton Example source code 
compared with GOF Singleton.
Example using Spring with Hibernate :
Example using Spring with Hibernate Framework and use
Current Session Context.
Example using Spring DAO with Hibernate :
Example using Spring DAO with Hibernate Framework Part 2.
Spring Framework MVC and Tiles :
Spring Framework MVC and Tiles with Example 
source code explained.
Spring Batch Framework Example :
Spring Batch Framework Example source code
 and Step by step code walkthrough
Spring Framework Web Example :
Spring Framework Web Example source code Explained.
Example using Spring with Hibernate :
Example using Spring with Hibernate Framework Part 1.
Spring Framework Remote Session Bean :
Spring Framework Example source code of
Remote Session Bean.
Interview Questions with answer on Spring Framework :
Interview Questions with answer on Spring Framework.
Spring Framework Example :
Spring Framework Example source code Explained.
Step by step code walkthrough
Spring Framework Web Example and WSDL :
Spring Framework Web Example source code
with WSDL.Step by step code walkthrough
Spring Framework Local Stateless Session bean :
Spring Framework Local Stateless Session bean with
example source code explained.
Example using Spring DAO with Hibernate :
Example using Spring DAO with Hibernate Framework.
Example using Spring with Hibernate :
Example using Spring with Hibernate Framework Part 2.
Spring Framework Web Example :
Spring Framework Web Example source code Explained.


References :
Tags: spring dao hibernate example
Tags: spring hibernate dao example
Tags: spring hibernate example 2
Tags: spring hibernate example current session context
Tags: spring hibernate example
Tags: Spring Interview Questions Answer
Tags: Spring Local SLBean
Tags: Spring MVC Tiles2
Tags: Spring Remote SLBean
Tags: Spring Singleton GOF Singleton Difference
Tags: spring web example
Tags: spring ws example
Tags: Spring
Tags: springws example wsdl



DISCLAIMER :
The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
techienjoy.com is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis,
without WARRANTIES or conditions of any kind, either express or implied, including, without
limitation, merchantability, or fitness for a particular purpose. You are solely responsible
for determining the appropriateness of using or refering this and assume any risks associated
with this.

In spite of all precautions taken to avoid any typo in these pages, there might be some 
issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
extends sincerest apologies to all our visitors for the same.



Android Examples || Android Examples

© Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions