DAO Framwork using Spring HibernteTemplate

Concept of Data Access layer

A data access layer follows the idea of “separation of concerns” whereby all of the logic required for your business logic to interact with your data layer (database) is isolated to a single set of classes (layer).

This allows you to more easily change the backend physical data storage technology (move from XML files to a database, or from SQL Server to Oracle or MySQL, for example) without having a large impact (and if done right having zero impact) to your business logic.

There are  lot of tools that will help you build your data layer. If you search for the phrase “object relational mapper” or “ORM” you should find some more detailed inform

Source – http://stackoverflow.com Discussions

DAO Design pattern in brief

Data Access Object encapsulates all the data access logic to create, retrieve, delete, and update data from a persistent store.

Data Access Object uses Transfer Object to send and receive data.

The Data Access Object pattern encapsulates access to a persistent store by managing the connection with the data store.

Adavantages of using DAO
Reduces code complexity in client
Improves code reuse
Provides easier migration to new data store

When to use DAO

Decouple data access from the business logic
Provide all data access from in a separate layer.

Generic DAO Layer Example

Following is DAO Framework designed using java.

Following are core components of it.
BaseDao.java
BusinessDaoImpl.java  (Implementation Class of BaseDao)

Business DAO Interface

Example :
EmployeeDao.java

Business DAO Impl

Example:
EmployeeDaoImpl

Test Program Using Spring 3.X /Hibernate 3.X / MySql

Source Code Examples in are as Follows

BaseDao.java


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

public interface BaseDao<T, PK extends Serializable> {

    public Serializable save(T newInstance);

    void update(T transientObject);

    void saveOrUpdate(T transientObject);

    void saveOrUpdateAll(List<T> transientObjectCollection);

    void delete(T persistentObject);

    public List<T> find() throws CustomException;

    public List<T> find(String propertyName, Object value);

    T findById(PK id) throws CustomException;

    public T search(String columnName, Object value);

    public Object exec(String query);

    public Object exec(String query,Object[] params);

}

BusinessDaoImpl.java


import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

public abstract class BusinessDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {

private static final String DATA_ACCESS_EXCEPTION_IN_FIND = "DataAccessException in  Find";

@Autowired
private HibernateTemplate hibernateTemplate;

protected Class<T> domainClass = getDomainClass();

protected abstract Class<T> getDomainClass();

public HibernateTemplate getHibernateTemplate() throws Exception {

return hibernateTemplate;
}

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;

}

@SuppressWarnings("unchecked")
public Serializable save(T t) {

return hibernateTemplate.save(t);

}

@SuppressWarnings("unchecked")
public void update(T t) {

hibernateTemplate.update(t);
}

@SuppressWarnings("unchecked")
public void saveOrUpdate(T t) {

hibernateTemplate.saveOrUpdate(t);
}

@SuppressWarnings("unchecked")
public void saveOrUpdateAll(List<T> t) {

hibernateTemplate.saveOrUpdateAll(t);
}

@SuppressWarnings("unchecked")
public void delete(T t) {

hibernateTemplate.delete(t);
}

@SuppressWarnings("unchecked")
public List<T> find() throws CustomException {

List<T> t = new ArrayList<T>();
try {
t = getHibernateTemplate().find("from " + getDomainClass().getName());
} catch (DataAccessException e) {
throw new CustomException(DATA_ACCESS_EXCEPTION_IN_FIND+"Error=>"+e.toString(),0001);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}

@SuppressWarnings("unchecked")
public List<T> find(String domainObjectField, Object value) throws CustomException {

List<T> t = new ArrayList<T>();
DetachedCriteria criteria = createDetachedCriteria();

criteria.add(Restrictions.eq(domainObjectField, value));

try {
t = getHibernateTemplate().findByCriteria(criteria);
} catch (DataAccessException e) {
throw new CustomException(DATA_ACCESS_EXCEPTION_IN_FIND+"Error=>"+e.toString(),0001);
} catch (Exception e) {
e.printStackTrace();
}
return t;

}

@SuppressWarnings("unchecked")
public T findById(PK id) throws CustomException {

T t = null;
try {

t = getHibernateTemplate().get(getDomainClass(), id);
} catch (Exception e) {
throw new CustomException(DATA_ACCESS_EXCEPTION_IN_FIND+"Error"+e.toString(),0001);
}
return t;
}

/**
*
*/
public T search(final String columnName, final Object value) {

return hibernateTemplate.execute(new HibernateCallback<T>() {

public T doInHibernate(Session session) throws HibernateException, SQLException {

return DataAccessUtils.objectResult(session.createCriteria(getDomainClass()).add(Restrictions.eq(columnName, value)).list(),
getDomainClass());
}
});
}

/**
* @param query
* @return
*/
public Object exec(final String query) {

return hibernateTemplate.execute(new HibernateCallback<Object>() {

public Object doInHibernate(Session session) throws HibernateException, SQLException {

return session.createQuery(query).list();
}

});
}

public Object exec(final String query, final Object[] params) {

System.out.println("Query====================>"+query);
return  hibernateTemplate.execute(new HibernateCallback<Object>() {
public Object doInHibernate(Session session)
throws HibernateException {

Query q = session.createQuery(query);
fillParams(q,params);
return q.list();

}
});
}

/**
* @return
*/
protected DetachedCriteria createDetachedCriteria() {

return DetachedCriteria.forClass(getDomainClass());

}

private void fillParams(Query q, final Object[] params) {

if (null != params) {

for (int i = 0; i < params.length; i++) {
q.setParameter(i, params[i]);

}
}
}

}

Business DAO Interface
eg : EmployeeDao.java


import java.io.Serializable;

public interface EmployeeDao extends BaseDao<Employee, Serializable>{

}

Business DAO Implementation Class
Eg: EmployeeDaoImpl


public class EmployeeDaoImpl extends BusinessDaoImpl<Employee, Serializable> implements EmployeeDao {

@Override
protected Class<Employee> getDomainClass() {
return Employee.class;
}

}

Advertisements
Tagged with: , , , , , ,
Posted in Uncategorized
4 comments on “DAO Framwork using Spring HibernteTemplate
  1. Taboo Subjects says:

    Awesome tutorial. This is just what I was looking for. Thanks.

  2. jayamali says:

    nice tutorial.Was very helpful

  3. Dinesha says:

    Very helpful tutorial…Thanks a lot.

  4. ManaraM says:

    Awesome stuff.. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: