Monday, June 10, 2013

Creating Generic Dao Class

Generic Interface:
============

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

/**
 * Base DAO interface that provide interface to basic database operations.
 * This class contains generic methods signatures that operate on tables
 *
 * @author laxman
 *
 * @param <T>
 */
public interface GenericDao<T> {

public Integer persist(Session session, T dataObject)
throws HibernateException;

public void attachDirty(Session session, T dataObject)
throws HibernateException;

public void attachClean(Session session, T dataObject)
throws HibernateException;

public void delete(Session session, T dataObject)
throws HibernateException;

public T merge(Session session, T dataObject)
throws HibernateException;

public T findById(Session session, Integer id, Class instanceType)
throws HibernateException;

public List<T> findByExample(Session session, T dataObject)
throws HibernateException;

public T findById(Session session, Long id, Class instanceType)
throws HibernateException;

public T findById(Session session, String id, Class instanceType)
throws HibernateException;

public T findById(Session session, Double id, Class instanceType)
throws HibernateException;

public T findById(Session session, BigDecimal id,
Class instanceType) throws HibernateException;
public List<Object> findByQuery(Session session,String query)throws HibernateException;
public List<T> findBy_Query(Session session,String query)throws HibernateException;


public Class<T> getType();



}


Implementation class:
=============


/**
 *
 */
package com.asman.diameter.dao.impl;

import static org.hibernate.criterion.Example.create;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.asman.diameter.dao.DiameterDao;



/**
 *
 * Useful class for creating a basic DAO. Typically you would extend this class and register your entities/pojos,
 * then provide higher-level data manipulation methods as desired.
 * <p>
 * This class contains generic methods to operate on entities.All methods are generic in nature that they are not tied to specific entity.
 * Handles all generic database operations (CURD) on provided entity
 *
 * <p>
 * Each DAO that extends from this base DAO should tie by with specific entity.
 * Each DAO should implement getType() method to make use of generic operations in this base DAO.
 * Each entity/POJO should extend {@link DomainObject} to be part of these methods.
 *
 * @author laxman
 *
 */
@Repository("genericDao")
@Transactional
public class GenericDaoImpl<T> implements GenericDao<T> {

private HibernateTemplate hibernateTemplate;

public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}

private SessionFactory sessionFactory;

@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
hibernateTemplate = new HibernateTemplate(sessionFactory);
}



private static final Log log = LogFactory.getLog(DiameterpDaoImpl.class);

/**
* Persist/save a POJO or an entity
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public Integer persist(Session session, T dataObject)
throws HibernateException {
log.debug("persisting Specific instance");
Transaction transaction=session.beginTransaction();
try {
Integer Id=(Integer) session.save(dataObject);
transaction.commit();
log.debug("persist successful");
return Id;
} catch (HibernateException re) {
log.error("persist failed", re);
throw re;
}
}

/**
* Merge entity and persist them in database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public T merge(Session session, T dataObject)
throws HibernateException {
log.debug("merging data instance");
try {
T result = (T) session.merge(dataObject);
log.debug("merge successful");
return result;
} catch (HibernateException re) {
log.error("merge failed", re);
throw re;
}
}

/**
* Attach a clean Entity
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public void attachClean(Session session, T dataObject)
throws HibernateException {
log.debug("attaching clean dataObject instance");
try {
session.lock(dataObject, LockMode.NONE);
log.debug("attach successful");
} catch (HibernateException re) {
log.error("attach failed", re);
throw re;
}
}

/**
* Attach modified entity and update Details in database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public void attachDirty(Session session, T dataObject)
throws HibernateException {
log.debug("attaching dirty dataObject instance");
try {
Transaction transaction=session.beginTransaction();
session.saveOrUpdate(dataObject);
transaction.commit();
log.debug("attach successful");
} catch (HibernateException re) {
log.error("attach failed", re);

System.out.println("exception::::::"+re);
throw re;
}
}

/**
* Delete specific entity from database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public void delete(Session session, T dataObject)
throws HibernateException {
log.debug("deleting dataObject instance");
try {
session.delete(dataObject);
log.debug("delete successful");
} catch (HibernateException re) {
log.error("delete failed", re);
throw re;
}
}

/**
* Delete specific entity from database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
public Integer delete_single_record(Session session, String queryString)
throws HibernateException {
log.debug("deleting dataObject instance");
try {

Query query =  session.createQuery(queryString);
return query.executeUpdate();
} catch (HibernateException re) {
log.error("get failed", re);

System.out.println("exceptionnnnnnnnnnn"+re);
throw re;
}
}
/**
* Fetch List of entity based on Example criteria
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public List<T> findByExample(Session session, T dataObject)
throws HibernateException {
log.debug("finding data instance by example");

try {
List<T> results = (List<T>) session
.createCriteria(dataObject.getClass())
.add(create(dataObject)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (HibernateException re) {
log.error("find by example failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type Integer
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, Integer id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
Integer i = id;
try {
T instance = (T) session.get(instanceType,i);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);

System.out.println("exceptionnnnnnnnnnnnnnn"+re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type Long
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, Long id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type string
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, String id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type double
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, Double id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type Bigdecimal
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, BigDecimal id,
Class instanceType) throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Save an entity to Database
* @param pojo a generic POJO that extends {@link DomainObject}
*/
public void save(T pojo){
getHibernateTemplate().save(pojo);
}

/**
* Save or Update an entity to Database
* @param pojo a generic POJO that extends {@link DomainObject}
*/
public void saveOrUpdate(T pojo){
getHibernateTemplate().saveOrUpdate(pojo);
}

/**
* Find list of entity that matches the query string
* @param session Hibernate session
* @param queryString condition to fetch entites
*/
@Override
public List<Object> findByQuery(Session session, String queryString)
throws HibernateException {
try {

Query query =  session.createQuery(queryString);
return query.list();
} catch (HibernateException re) {
log.error("get failed", re);

System.out.println("exceptionnnnnnnnnnn"+re);
throw re;
}
}






/**
* This method provides the type of the entity passed to base class
* All sub classes that extends the base DAO should override it and return specific entity type.
*
*/
public Class<T> getType(){
return null;
}


@Override
public List<T> findBy_Query(Session session, String queryString)
throws HibernateException {
try {
Query query =  session.createQuery(queryString);
return query.list();
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}


}



No comments:

Post a Comment