DAO

最近想玩会,写点东西练下手,还没有经过测试,这个肯定不够完美,做个自已的备份用。

有人想用请自已测一下吧,有时间再继续进行修改完善。



package com.zhenjw.dao;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zhenjw.common.HibernateSessionFactory;
import com.zhenjw.common.QueryResult;

/**
 * Hibernate base DataBase Access Object
 * @author zjw
 * @datetime Jun 18, 200910:00:19 PM
 */

public class BaseDao {
	
	private Logger logger=Logger.getLogger(this.getClass());

	/**
	 * 
	 */
	public BaseDao() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 功能:保存数据
	 * @param entity
	 * @throws DaoException
	 */
	public void create(Object entity)throws DaoException
	{
		logger.debug("create , entity.classname"+entity.getClass().getName());
		
		Session session=null;
		
		Transaction tr=null;
		
		boolean commitFlag=false;
		
		try{
			
			session=this.getSession();
			
			tr=session.beginTransaction();
			
			tr.begin();
			
			session.save(entity);
			
			tr.commit();
			
			commitFlag=true;
			
			session.flush();
			
		}catch(HibernateException e)
		{	
			this.haveHibernateException("basedao.create.error", e);
		}
		finally{
			
			this.closeSession(session, tr, commitFlag);
			
		}
		
	}
	
	/**
	 * 功能:修改数据
	 * @param entity
	 * @throws DaoException
	 */
	public void update(Object entity)throws DaoException
	{
		logger.debug("update , entity.classname"+entity.getClass().getName());
		
		Session session=null;
		
		Transaction tr=null;
		
		boolean commitFlag=false;
		
		try{
			
			session=this.getSession();
			
			tr=session.beginTransaction();
			
			tr.begin();
			
			session.update(entity);
			
			tr.commit();
			
			commitFlag=true;
			
			session.flush();
			
		}catch(HibernateException e)
		{
			this.haveHibernateException("basedao.update.error", e);
		}
		finally{
			
			this.closeSession(session, tr, commitFlag);
			
		}
		
	}

	/**
	 * 功能:根据ID得到对象
	 * @param clazz
	 * @param id
	 * @return Object
	 * @throws DaoException
	 */
	public Object getEntityById(Class clazz,long id)throws DaoException
	{
		Session session=null;
		
		Object result=null;
		
		try{
		
			result=session.get(clazz, id);
			
		}catch(HibernateException e)
		{	
			this.haveHibernateException("basedao.getEntityById.error", e);
			
		}finally
		{
			this.closeSession(session);
			
		}
		
		return result;
		
	}

	/**
	 * 功能:删除记录
	 * @param tableName    表名
	 * @param idFieldName  表的ID字段的名称
	 * @param id           ID数组
	 * @throws DaoException
	 */
	public void delete(String tableName ,String idFieldName,long[] id)throws DaoException
	{
		logger.debug(" delete  tableName="+tableName+"  ,idFieldName="+ idFieldName );
		
		if(id==null)
			
			logger.debug(" id is null ");
		
		else
		{
			StringBuilder idB=new StringBuilder();
			
			for(int i=0 ;i<id.length;i++)
			{
				if(i>0)
					
					idB.append(",");
				
				idB.append(id[i]);
					
			}
			
			logger.debug("  id ="+idB.toString());
			
			Session session=null;
			
			Transaction tr=null;
			
			boolean commitFlag=false;
			
			try{
				
				StringBuilder deleteSql=new StringBuilder();
				
				deleteSql.append("  delete from ").append(tableName)
				 		 .append("  where ").append( idFieldName ).append(" in ( "+idB.toString()+" ) ");
				
				logger.debug("deleteSql="+ deleteSql.toString());
				
				session=this.getSession();
				
				tr=session.beginTransaction();
				
				tr.begin();
				
				session.createSQLQuery( deleteSql.toString()).executeUpdate();
				
				tr.commit();
				
				commitFlag=true;
				
				session.flush();
				
			}catch(HibernateException e)
			{	
				this.haveHibernateException("basedao.delete.error", e);
				
			}finally{

				this.closeSession(session, tr, commitFlag);

			}
		} 
		
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的SQL
	 * @param queryData  查询数据的SQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryBySql(StringBuilder queryCount,StringBuilder queryData,int pageNo,int pageSize)throws DaoException
	{
		return this.queryBySql(queryCount, queryData, pageNo, pageSize, null);
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的SQL
	 * @param queryData  查询数据的SQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @param params     参数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryBySql(StringBuilder queryCount,StringBuilder queryData,int pageNo,int pageSize,List params)throws DaoException
	{
		return this.queryBySql(queryCount.toString(), queryData.toString(), pageNo, pageSize, params);
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的SQL
	 * @param queryData  查询数据的SQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryBySql(String queryCount,String queryData,int pageNo,int pageSize)throws DaoException
	{
		return this.queryBySql(queryCount, queryData, pageNo, pageSize, null);
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的SQL
	 * @param queryData  查询数据的SQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @param params     参数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryBySql(String queryCount,String queryData,int pageNo,int pageSize,List params)throws DaoException
	{
		QueryResult result=new QueryResult(); 
		
		logger.debug("queryBySql  \n queryCount="+queryCount+" \n queryData="+queryData+" \n pageNo ="+pageNo+" \n pageSize"+pageSize);
		
		this.writeLogger(null, params);
		
		Session session=null;
		
		try{
			
			session=this.getSession();
			
			int totalRow=this.getRowCountNum(session.createSQLQuery(queryCount).list() );
			
			result.setTotalRow(totalRow);
			
			result.setPageSize(pageSize);
			
			int totalPage=result.getPageNo();
			
			if(totalPage<pageNo)
				
				pageNo=totalPage;
			
			result.setPageNo(pageNo);
			
			//查询数据
			
			SQLQuery query=session.createSQLQuery(queryData);
			
			this.setParamters(params, query);
			
			this.setTurnPageParam(pageNo, pageSize, query);
			
			result.setDataList(query.list());
			
		}catch(HibernateException e)
		{
			this.haveHibernateException("basedao.queryBySql.error", e);
			
		}finally{
			
			this.closeSession(session);
		}
		
		return result;
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的HQL
	 * @param queryData  查询数据的HQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryByHql(StringBuilder queryCount,StringBuilder queryData,int pageNo,int pageSize)throws DaoException
	{
		return this.queryByHql(queryCount, queryData, pageNo, pageSize, null);
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的HQL
	 * @param queryData  查询数据的HQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @param params     参数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryByHql(StringBuilder queryCount,StringBuilder queryData,int pageNo,int pageSize,List params)throws DaoException
	{
		return this.queryByHql(queryCount.toString(), queryData.toString(), pageNo, pageSize, params);
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的HQL
	 * @param queryData  查询数据的HQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryByHql(String queryCount,String queryData,int pageNo,int pageSize)
	{
		return this.queryByHql(queryCount, queryData, pageNo, pageSize, null);
	}
	
	/**
	 * 功能:分页查询
	 * @param queryCount 查询记录总数的HQL
	 * @param queryData  查询数据的HQL
	 * @param pageNo     当前页的页码
	 * @param pageSize   每页显示的记录条数
	 * @param params     参数
	 * @return QueryResult
	 * @see com.zhenjw.common.QueryResult
	 * @throws DaoException
	 */
	public QueryResult queryByHql(String queryCount,String queryData,int pageNo,int pageSize,List params)
	{
		QueryResult result=new QueryResult(); 
		
		logger.debug("queryByHql  \n queryCount="+queryCount+" \n queryData="+queryData+" \n pageNo ="+pageNo+" \n pageSize"+pageSize);
		
		this.writeLogger(null, params);
		
		Session session=null;
		
		try{
			
			session=this.getSession();
			
			int totalRow=this.getRowCountNum(session.createQuery(queryCount).list() );
			
			result.setTotalRow(totalRow);
			
			result.setPageSize(pageSize);
			
			int totalPage=result.getPageNo();
			
			if(totalPage<pageNo)
				
				pageNo=totalPage;
			
			result.setPageNo(pageNo);
			
			//查询数据
			
			Query query=session.createQuery(queryData);
			
			this.setParamters(params, query);
			
			this.setTurnPageParam(pageNo, pageSize, query);
			
			result.setDataList(query.list());
			
		}catch(HibernateException e)
		{
			this.haveHibernateException("basedao.queryByHql.error", e);
			
		}finally
		{
			this.closeSession(session);
		}
		
		return result;
	}
		
	/**
	 * 功能:查询数据
	 * @param queryData  查询数据的SQL语句
	 * @return List
	 * @throws DaoException
	 */
	public List queryBySql(String queryData)throws DaoException
	{
		return this.queryBySql(queryData, null);
	}
	
	/**
	 * 功能:查询数据
	 * @param queryData  查询数据的SQL语句
	 * @return List
	 * @throws DaoException
	 */
	public List queryBySql(StringBuilder queryData)throws DaoException
	{
		return this.queryBySql(queryData, null);
	}
	 
	/**
	 * 功能:查询数据
	 * @param queryData 查询数据的SQL语句
	 * @param params    参数
	 * @return List
	 * @throws DaoException
	 */
	public List queryBySql(String queryData,List params)throws DaoException
	{
		logger.debug("  queryBySql  queryData="+queryData);
		
		this.writeLogger(null, params);
		
		List result=null;
		
		Session session=null;
		
		try{
			
			session=this.getSession();
			
			SQLQuery query=session.createSQLQuery(queryData);
			
			this.setParamters(params, query);
			
			result=query.list();
			
		}catch(HibernateException e)
		{
			
			this.haveHibernateException("basedao.queryBySql.error", e);
			
		}finally
		{	
			this.closeSession(session);
		}
		
		return result;
		
	}
	
	/**
	 * 功能:查询数据
	 * @param queryData 查询数据的SQL语句
	 * @param params    参数
	 * @return List
	 * @throws DaoException
	 */
	public List queryBySql(StringBuilder queryData,List params)throws DaoException
	{
		return this.queryBySql(queryData.toString(), params);
	}
	
	/**
	 * 功能:查询数据
	 * @param queryData  查询数据的HQL语句
	 * @return List
	 * @throws DaoException
	 */
	public List queryByHql(String queryData)throws DaoException
	{

		return this.queryByHql(queryData, null);
		
	}
	
	/**
	 * 功能:查询数据
	 * @param queryData  查询数据的HQL语句
	 * @return List
	 * @throws DaoException
	 */
	public List queryByHql(StringBuilder queryData)throws DaoException
	{

		return this.queryByHql(queryData, null);
		
	}
	
	/**
	 * 功能:查询数据
	 * @param queryData 查询数据的HQL语句
	 * @param params    参数
	 * @return List
	 * @throws DaoException
	 */
	public List queryByHql(String queryData,List params)throws DaoException
	{
		logger.debug("  queryByHql  queryData="+queryData);
	
		this.writeLogger(null, params);
		
		List result=null;
		
		Session session=null;
		
		try{
			
			session=this.getSession();
			
			Query query=session.createQuery(queryData);
			
			this.setParamters(params, query);
			
			result=query.list();
			
		}catch(HibernateException e)
		{
			this.haveHibernateException("basedao.queryByHql.error", e);
			
		}finally
		{
			
			this.closeSession(session);
			
		}
		
		return result;
	}
	
	/**
	 * 功能:查询数据
	 * @param queryData 查询数据的HQL语句
	 * @param params    参数
	 * @return List
	 * @throws DaoException
	 */
	public List queryByHql(StringBuilder queryData,List params)throws DaoException
	{
		return this.queryByHql(queryData.toString(), params);
	}
	
	/**
	 * 功能:执行更新数据的SQL语句
	 * @param updataSql SQL语句
	 * @throws DaoException
	 */
	public void updateBySql(StringBuilder updataSql)throws DaoException
	{
		this.updateBySql(updataSql,null);
	}
	
	/**
	 * 功能:执行更新数据的SQL语句
	 * @param updataSql SQL语句
	 * @param params    参数
	 * @throws DaoException
	 */
	public void updateBySql(StringBuilder updataSql,List params)throws DaoException
	{
		this.updateBySql(updataSql.toString(), params);
	}
	
	/**
	 * 功能:执行更新数据的SQL语句
	 * @param updataSql SQL语句
	 * @throws DaoException
	 */
	public void updateBySql(String updataSql)throws DaoException
	{
		this.updateBySql(updataSql,null);
	}
	
	/**
	 * 功能:执行更新数据的SQL语句
	 * @param updataSql SQL语句
	 * @throws DaoException
	 */
	public void updateBySql(String updataSql,List params)throws DaoException
	{
		logger.debug(" updateBySql    updataSql="+updataSql);
		
		this.writeLogger(null, params);
		
		Session session=null;
		
		Transaction tr=null;
		
		boolean commitFlag=false;
		
		try{
			
			session=this.getSession();
			
			tr=session.beginTransaction();
			
			tr.begin();
			
			SQLQuery query=session.createSQLQuery(updataSql);
			
			this.setParamters(params, query);

			query.executeUpdate();
			
			tr.commit();
			
			commitFlag=true;
			
		}catch(HibernateException e)
		{
			this.haveHibernateException("basedao.updateBySql.error", e);
			
		}finally
		{
			this.closeSession(session, tr, commitFlag);
		}
	}
	
	/**
	 * 功能:执行更新数据的 HQL语句
	 * @param updataSql HQL语句
	 * @throws DaoException
	 */
	public void updateByHql(StringBuilder updataHql)throws DaoException
	{
		this.updateByHql(updataHql, null);
		
	}
	
	public void updateByHql(StringBuilder updataHql,List params)throws DaoException
	{
		this.updateByHql(updataHql.toString(), params);
	}
	
	public void updateByHql(String updataHql)throws DaoException
	{
		this.updateByHql(updataHql, null);
		
	}
	
	public void updateByHql(String updataHql,List params)throws DaoException
	{

		logger.debug(" updateByHql    updataHql="+updataHql);
		
		this.writeLogger(null, params);
		
		Session session=null;
		
		Transaction tr=null;
		
		boolean commitFlag=false;
		
		try{
			
			session=this.getSession();
			
			tr=session.beginTransaction();
			
			tr.begin();
			
			Query query=session.createQuery(updataHql);
			
			this.setParamters(params, query);

			query.executeUpdate();
			
			tr.commit();
			
			commitFlag=true;
			
		}catch(HibernateException e)
		{	
			this.haveHibernateException("basedao.updateByHql.error", e);
			
		}finally
		{
			this.closeSession(session, tr, commitFlag);
		}
	
	}
	
	public void setParamters(List params,SQLQuery query)
	{
		if(params!=null)

			for(int i=0;i<params.size();i++)
			{
				this.setParamter(i,params.get(i), query);
			}
	}
	
	public void setParamters(List params,Query query)
	{
		if(params!=null)

			for(int i=0;i<params.size();i++)
			{
				this.setParamter(i,params.get(i), query);
			}
	}
	
	public void setParamter(int i,Object o ,SQLQuery query)
	{
		if(o instanceof java.util.Date)
		{
			query.setTimestamp(i, (java.util.Date)o);
			
		}else
		{
			query.setParameter(i,o);
		}
	}
	
	public void setParamter(int i,Object o ,Query query)
	{
		if(o instanceof java.util.Date)
		{
			query.setTimestamp(i, (java.util.Date)o);
			
		}else
		{
			query.setParameter(i,o);
		}
	}
	
	public void setTurnPageParam(int pageNo,int pageSize,SQLQuery query)
	{
		if(pageNo>0&&pageSize>0)
		{
			query.setFirstResult((pageNo-1)*pageSize);
			query.setMaxResults(pageSize);
		}
	}
	
	public void setTurnPageParam(int pageNo,int pageSize,Query query)
	{
		if(pageNo>0&&pageSize>0)
		{
			query.setFirstResult((pageNo-1)*pageSize);
			query.setMaxResults(pageSize);
		}
	}
	
	protected int getRowCountNum(List list)
	{
		int result=0;
		
		try{
			
			result=Integer.parseInt( list.get(0).toString());
			
		}catch(Exception e)
		{
			
		}	
		
		return result;
	}
	
	protected void writeLogger(String messageName,List params)
	{
		if(messageName==null)
			
			messageName=" params = ";
		
		StringBuilder paramsB=new StringBuilder();
		
		if(params!=null)
		{
			
			for(int i=0;i<params.size();i++)
			{
				if(i>0)
					paramsB.append(",");
				
				paramsB.append(this.getParamValue(params.get(i)));
					
			} 
			
			logger.debug(messageName+"   ="+paramsB.toString());
			
		}else
		{
			logger.debug(messageName+"  is null ");
		}
		
	}
	
	protected Object getParamValue(Object o)
	{
		Object result=o;
		
		if(o instanceof java.util.Date )
		{
			result=this.fomateDate((java.util.Date)o);
		}
		
		return result;
	}
	
	protected String fomateDate(Date date)
	{
		String result="";
	
		try{
		
			java.text.SimpleDateFormat formate=new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		 
			result=formate.format(date);
			
		}catch(Exception e)
		{
			logger.debug(e.getMessage(), e);
		} 
		
		return result;
	}
	
	public static void main(String []args)
	{

		Date date=null;
		
		java.text.SimpleDateFormat formate=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 
		System.out.println(formate.format(date) );
		
		 
	}
	
	public Session getSession()
	{  
		return  HibernateSessionFactory.getSession();
	}
	
	public void closeSession(Session session)
	{
		if(session!=null&&session.isOpen())
			
			session.close();
		
		session=null;
	}
	
	public void closeSession(Session session,Transaction tr,boolean commitFlag)
	{
		if(!commitFlag&&tr!=null)
		{
			try{
				
				tr.rollback();
			}catch(Exception e)
			{
				logger.debug(e.getMessage(),e);
			}
		}
		
		this.closeSession(session);
	}
	
	public void haveHibernateException(String key,HibernateException e)
	{
		new DaoException(logger,key, e);
	}

}

你可能感兴趣的:(DAO,apache,sql,Hibernate,log4j)