hibenate 팬 베이스 DAO

34546 단어
 
 

baseDAO

package com.dg11185.shgw.DAO.common;

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

import org.hibernate.Session;

import com.dg11185.shgw.utils.PagingParams;
import com.dg11185.shgw.utils.PagingResults;

/**
 *   DAO    
 * @author    
 * @since 1.0  
 * @Copyright 2013       All rights reserved.
 */
public interface BaseDao<T> {
	
	/**
	 *   ID    
	 * 
	 * @param entityClass      
	 * @param id
	 * @return     
	 */
	public T findById(Class<T> entityClass,Serializable id);
	
	/**
	 *         
	 * 
	 * @param entityClass      
	 * @return       
	 */
	public List findAll(Class entityClass);

    /**
     *       
     *            
     * @param entityClass      
     * @param orderBy     
     * @param isAsc    ?
     * @return       
     */
    public List findAll(Class entityClass, String orderByProperty, boolean isAsc);
    
    /**
     *       (     ,     ,   null)
     *            
     * @param entityClass      
     * @return       
     */
    public List<T> findByExample(Object entity);
    
    /**
     *      
     * 
     * @param hql  
     * @param params     
     * @return       
     */
    public List find(String hql,Object... params);

    /**
     *      
     * 
     * @param hql  
     * @param entityClass      
     * @return     
     */
	public Object findObj(String hql,Object...params);
    
	/**
	 *         
	 * @param entityClass     
	 * @param    
	 * @param  
	 * @return       
	 */
    public List findByProperty(Class entityClass,String propertyName,Object value);
    
    /**
     *     
     * 
  	 * @param   params        
  	 * @return        
     */
    public PagingResults paging(final PagingParams params) ;
    
    /**
     *     
     * @param obj     
     * 
     */
    public void save(Object obj);
    
    /**
     *   /    
     * @param entityClass      
     * @param obj     
     * @return   /      
     */
    public T merge(Class<T> entityClass,Object obj);
    
    /**
     *     
     * @param obj     
     */
    public void update(Object obj);
    
    /**
     *     
     * @param obj     
     */
    public void delete(Object obj);
    
    /**
     *     
     * @param entityClass      
     * @param id 
     */
    public void deleteById(Class entityClass,Serializable id);
    
    /**
     *   ID      
     * @param entityClass
     * @param ID    
     * @param ids       1,2,3        'hwt001','hwt002'
     */
    public void deleteByIds(Class entityClass, String idName , Serializable[] ids);
    
    /**
     *       
     * @objs          
     */
    public void batchUpdate(final List objs);
    
    /**
     *       
     * @objs          
     */
    public void batchInsert(final List objs);
    
    /**
     *     session
     * @return session
     */
    public Session getCurrentSession();
    
    /**
     *     
     */
    public void flush();
    
    /**
     *         
     */
    public void clear();
    
}


     ,  DAO      
package com.dg11185.shgw.DAO.common;


import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import javax.annotation.Resource;


import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


import com.dg11185.shgw.common.ConfigConstants;
import com.dg11185.shgw.utils.PagingParams;
import com.dg11185.shgw.utils.PagingResults;


/**
 *   DAO   
 * 
 * @since 1.0
 * @author    
 * @Copyright 2013       All rights reserved.
 */
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {


	@Override
	protected void initDao() throws Exception {
		// nothing
	}


	/**
	 *   sessionFactory
		 * @param sessionFactory
	 */
	@Resource(name = "sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}


	/**
	 *   ID    
		 * @param entityClass
	 *                 
	 * @param id
	 * @return     
	 */
	@Override
	public T findById(Class<T> entityClass, Serializable id) {
		return entityClass.cast(super.getHibernateTemplate().get(entityClass,
				id));
	}


	/**
	 *       (     ,     ,   null)            
		 * @param entityClass
	 *                 
	 * @return       
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findByExample(Object entity) {
		return getHibernateTemplate().findByExample(entity);
	}


	/**
	 *         
		 * @param entityClass
	 *                 
	 * @return       
	 */
	@Override
	public List findAll(Class entityClass) {
		String queryString = "from " + entityClass.getSimpleName();
		return super.getHibernateTemplate().find(queryString);
	}


	/**
	 *                   
		 * @param entityClass
	 *                 
	 * @param orderBy
	 *                
	 * @param isAsc
	 *               ?
	 * @return       
	 */
	@Override
	public List findAll(Class entityClass, String orderByProperty, boolean isAsc) {
		return isAsc ? super.getHibernateTemplate().findByCriteria(
				DetachedCriteria.forClass(entityClass).addOrder(
						Order.asc(orderByProperty))) : super
				.getHibernateTemplate().findByCriteria(
						DetachedCriteria.forClass(entityClass).addOrder(
								Order.desc(orderByProperty)));
	}


	/**
	 *      
		 * @param entityClass
	 *                 
	 * @param hql  
	 * @param params
	 *                
	 * @return       
	 */
	@SuppressWarnings({ "rawtypes" })
	@Override
	public List find(String hql, Object... params) {
		return getHibernateTemplate().find(hql, params);
	}


	/**
	 *      
		 * @param entityClass
	 *                 
	 * @param hql  
	 * @return       
	 */
	@SuppressWarnings({ "rawtypes" })
	public Object findObj(String hql, Object... params) {
		List list = getHibernateTemplate().find(hql, params);
		if (list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}


	/**
	 *         
		 * @param entityClass
	 *                
	 * @param    
	 * @param  
	 * @return       
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List findByProperty(Class entityClass, String propertyName,
			Object value) {
		String queryString = "from " + entityClass.getSimpleName()
				+ " as model where model." + propertyName + "= ?";
		return super.getHibernateTemplate().find(queryString, value);
	}


	/**
	 *     
		 * @param allSizeHql
	 *                     hql  
	 * @param queryListHql
	 *                  hql  
	 * @param page
	 *                        
	 * @param size
	 *                       
	 * @return Map<String,Object>          currentPage ==        pages ==
	 *                  allSize ==       list ==        
	 */
	/**
	 *     
		 * @param      
	 * @return      
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public PagingResults paging(final PagingParams params) {
		return (PagingResults) getHibernateTemplate().execute(
				new HibernateCallback() {
					@Override
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						int currentPage = params.getNextPage();


						Query query = session.createQuery(params
								.getAllSizeHql());
						//     
						Integer allSize = Integer.parseInt(query.list().get(0)
								.toString());
						//         
						int size = params.getPageSize();
						Integer pages = allSize % size == 0 ? allSize / size
								: allSize / size + 1;


						if (currentPage > pages) {
							currentPage = pages;
						} else if (currentPage <= 0) {
							currentPage = 1;
						}


						//      list
						Query listQuery = session.createQuery(params
								.getQueryHql());
						listQuery.setFirstResult((currentPage - 1) * size)
								.setMaxResults(size);
						List list = listQuery.list();
						PagingResults results = new PagingResults();
						results.setCurrentPage(currentPage);
						results.setTotalPages(pages);
						results.setTotalSize(allSize);
						results.setList(list);


						return results;
					}
				});
	}


	/**
	 *     
		 * @param allSizeHql
	 *                     hql  
	 * @param queryListHql
	 *                  hql  
	 * @param page
	 *                        
	 * @param size
	 *                       
	 * @return Map<String,Object>          currentPage ==        pages ==
	 *                  allSize ==       list ==        
	 */
	/**
	 *     
		 * @param      
	 * @return      
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public PagingResults paging(final PagingParams params,
			final List<String> columns, final List<?> args) {
		return (PagingResults) getHibernateTemplate().execute(
				new HibernateCallback() {
					@Override
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						int currentPage = params.getNextPage();


						Query query = session.createQuery(params
								.getAllSizeHql());
						for (int index = 0; index < columns.size(); index++) {
							query.setParameter(columns.get(index),
									args.get(index));
						}
						//     
						Integer allSize = Integer.parseInt(query.list().get(0)
								.toString());
						//         
						int size = params.getPageSize();
						Integer pages = allSize % size == 0 ? allSize / size
								: allSize / size + 1;


						if (currentPage > pages) {
							currentPage = pages;
						} else if (currentPage <= 0) {
							currentPage = 1;
						}


						//      list
						Query listQuery = session.createQuery(params
								.getQueryHql());
						for (int index = 0; index < columns.size(); index++) {
							listQuery.setParameter(columns.get(index),
									args.get(index));
						}
						listQuery.setFirstResult((currentPage - 1) * size)
								.setMaxResults(size);
						List list = listQuery.list();
						PagingResults results = new PagingResults();
						results.setCurrentPage(currentPage);
						results.setTotalPages(pages);
						results.setTotalSize(allSize);
						results.setList(list);


						return results;
					}
				});
	}


	/**
	 *     
		 * @param obj
	 *                
		 */
	@Override
	public void save(Object obj) {
		super.getHibernateTemplate().save(obj);
	}


	/**
	 *     
		 * @param entityClass
	 *                 
	 * @param obj
	 *                
	 * @return       
	 */
	@Override
	public T merge(Class<T> entityClass, Object obj) {
		return entityClass.cast(super.getHibernateTemplate().merge(obj));
	}


	/**
	 *     
		 * @param obj
	 *                
	 */
	@Override
	public void update(Object obj) {
		super.getHibernateTemplate().update(obj);
	}


	/**
	 *     
		 * @param obj
	 *                
	 */
	@Override
	public void delete(Object obj) {
		super.getHibernateTemplate().delete(obj);
	}


	/**
	 *     
		 * @param entityClass
	 *                 
	 * @param id
	 */
	@Override
	public void deleteById(Class entityClass, Serializable id) {
		super.getHibernateTemplate().delete(findById(entityClass, id));
	}


	/**
	 *   ID      
		 * @param entityClass
	 * @param ids
	 *                  1,2,3       'hwt001','hwt002'
	 */
	@Override
	public void deleteByIds(Class entityClass, String idName, Serializable[] ids) {
		String id = "?";
		for (int i = 0; i < ids.length - 1; i++) {
			id = id + ",?";
		}


		String hql = "delete from " + entityClass.getSimpleName() + " where "
				+ idName + " in (" + id + ")";
		getHibernateTemplate().bulkUpdate(hql, ids);
	}


	/**
	 *     session
		 * @return session
	 */
	@Override
	public Session getCurrentSession() {
		return super.getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
	}


	/**
	 *     
	 */
	@Override
	public void flush() {
		super.getHibernateTemplate().flush();


	}


	/**
	 *         
	 */
	@Override
	public void clear() {
		super.getHibernateTemplate().clear();
	}


	/**
	 *            
		 * @author IRun
	 * @param sheetcode
	 *                , 01
	 * @param columnname
	 *              ,  pojo      
	 * @param t
	 *              
	 * @return     
	 */
	public String getApplyNo(String sheetcode, Class<?> t, String columnname) {
		//     
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		//    
		String seqName = null;
		//      
		if (ConfigConstants.PURFORM_TYPE.equals(sheetcode)) {
			seqName = "SEQ_PURCHASING";
		}
		if (ConfigConstants.INPFORM_TYPE.equals(sheetcode)) {
			seqName = "SEQ_ENTERSTORE";
		}
		if (ConfigConstants.OUTFORM_TYPE.equals(sheetcode)) {
			seqName = "SEQ_STOCKREMOVAL";
		}
		if (ConfigConstants.RTFORM_TYPE.equals(sheetcode)) {
			seqName = "SEQ_RETURNTOCLIENT";
		}
		if (ConfigConstants.ECGFORM_TYPE.equals(sheetcode)) {
			seqName = "SEQ_EXCHANGETOCLIENT";
		}
		if (ConfigConstants.RTSUPGFORM_TYPE.equals(sheetcode)) {
			seqName = "SEQ_RETURNTOSUPPILER";
		}
		if (ConfigConstants.ECSUPGFORM_TYPE.equals(sheetcode)) {
			seqName = "SEQ_EXCHANGETOSUPPLIER";
		}
		//              
		String sql = "select " + seqName + ".NEXTVAL as id from dual";
		Session session = getCurrentSession();
		Long id = (Long) session.createSQLQuery(sql)
				.addScalar("id", Hibernate.LONG).uniqueResult();


		//       
		String runingNum = id.toString();
		Integer no = Integer.parseInt(runingNum) + 1;
		String noStr = no.toString();
		if (noStr.length() == 1) {
			noStr = "000" + noStr;
		} else if (noStr.length() == 2) {
			noStr = "00" + noStr;
		} else if (noStr.length() == 3) {
			noStr = "0" + noStr;
		}
		return sdf.format(new Date()) + sheetcode + noStr;
	}


	/**
	 *     
		 * @param objs
	 *                     
	 */
	@Override
	public void batchUpdate(final List objs) {
		getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				int len = objs.size();
				for (int i = 0; i < len; i++) {
					session.merge(objs.get(i));
					if (i % 15 == 0) {
						session.flush();
						session.clear();
					}
				}
				return null;
			}
		});
	}


	/**
	 *     
		 * @param objs
	 *                     
	 */
	@Override
	public void batchInsert(final List objs) {
		getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				int len = objs.size();
				for (int i = 0; i < len; i++) {
					session.save(objs.get(i));
					if (i % 15 == 0) {
						session.flush();
						session.clear();
					}
				}
				return null;
			}
		});
	}


}

좋은 웹페이지 즐겨찾기