| |
Struts Tutorials:
Struts2 Tag CheckBoxList , Checkbox, Iterator, IF
Struts2 Tag Library Example
Struts2 Tiles Example
Struts2 Tiles I18N Example
Struts2 Questions
Struts Tiles I18N Example
Struts Eclipse MVC
Struts2 Tags
Struts2 Example and Tutorial
Struts MVC
Struts2 Validation
Hibernate Tutorials:
Hibernate Case Study
Class Hierarchy Persist Example
Using Hibernate Interceptor
Hibernate Questions with Answer
Hibernate Many-to-Many Mapping Example
Hibernate one-to-many Mapping Example
Hibernate and ORM tools
Spring Hibernate Example
Hibernate SessionFactory Example
Hibernate Mapping Class Hierarchy
Hibernate Questions
Hibernate SessionFactory Questions
Spring Hibernate Example:
Spring Hibernate Case Study
Written By : Amit
Title :
Hiberate Spring Tutorial
Description :
Example code More...
|
Written By : Amit
Title :
Hibernate SessionFactory
Description :
Example code More...
|
Written By : ISHTEK
Title :
Design Spring Hibernate
Description :
Example Case study More...
|
Written By : Amit
Title :
Hiberate DAOSupport
Description :
Hiberate Template More...
|
Written By : Amit
Title :
HiberateDAOSupport Example
Description :
Design discussion More...
|
| Tags/Keywords : Spring HiberateDAOSupport Example Author : Amit Date (Year/Month/Date): 2010-03-28
Extending Spring's HibernateDAO Support with an example | |
Please be informed that NONE of the design/code/matter from this page is claiming to be some
sort of best practice and we DO NOT expect any of our visitor/reader of this page to assume
this as some sort of best practice for any context and should not be using this as it is
without appropriate evaluation.
This page intends only to provide bits and pieces of known ways for doing some sort of example
and may not be fit for any other purpose.
In spite of all precautions taken to provide accurate and avoid any typo in these pages,
there might be some issues like grammatical mistakes and typo being observed in these pages,
We extend our sincerest apologies for the same.
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 :
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).
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.
|
|
|
|
| Home >>> Spring Hibernate Example >>> HiberateDAOSupport Example >>> Design discussion |
|
|
Visitor/User referred related external URL:
(Visible upon review and approved by this site Administrator)
|
|
|
|
|
<- requires login | Log in or Register | |
Copyright © 2008-2010, Interview-Questions-Tips-Forum, All Rights Reserved. | CONTACT PRIVACY POLICY DISCLAIMER |
| |  |
Oracle and Java are registered trademarks of Oracle and/or its affiliates.
Other names may be trademarks of their respective owners
This web site's Terms of Use and Disclaimer :
This web site provides some of the information about various technologies, example code, tips, tutorials etc. Like any printed materials,
content of these pages may become out of date over a period of time. Therefore all visitor/users of this web site are requested/advised
to refer to the originating parties/sources for the latest changes and happenings for detailed information. This information is not
intended to be a substitute for the original reference provided by the originating parties/sources. These examples with source code or
without source code, have not been thoroughly tested under all conditions. Interview-questions-tips-forum.net therefore, cannot guarantee
or imply reliability of these example source code or programs.
By accessing and using this website in any ways, including, without limitation, browsing the website pages, using any information, using
any content and/or downloading any materials, you agree to and are bound by the terms of use described in this page and Usage Terms and Conditions.
If you do not agree to all of the terms and conditions contained in the terms of use described in this page and
Usage Terms and Conditions, do not use this website in any manner. If you are using the website on behalf of your
employer, you represent that you are authorized to accept these Terms of Use on your employer's behalf.
All Trademarks are property of their respective owner. Appropriate measure is being taken for providing accurate and up-to-date
information but like any printed materials, these blog(s)/contents may eventually be outdated one day, so if you are using any of these
information, please refer original content/documentation from respective sources. And under no circumstances shall the Author of these
contents and/or this web site be liable for any loss, damage, expense incurred or suffered which is claimed to have occurred because of
usage of the contents of this web site. If you have any questions/queries/feedback/suggestions then please write to this web site owner
at contact.
|  |
|
|
|
|
|