`

关于BaseDaoImpl的简单示例

 
阅读更多

          示例:实现basedao

package com.cn.base.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.fang.base.dao.IBaseDao;
import com.fang.util.HibernateSessionFactory;
import com.fang.util.Page;

public abstract class BaseDaoImpl<T> implements IBaseDao<T> {
	private Log log = LogFactory.getLog(this.getClass());
	private Class<T> entityClass;

    @SuppressWarnings("unchecked")
    public BaseDaoImpl() {
    	//1、尝试基本的获取对象实体类对象方法
    	entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    	/*2、或尝试这个关于代理的如果有T的实例t,创建代理后的实例proxiedT,你拿到proxiedT 后怎么 才能拿到 t?
    		通过代理生成的类应该是继承了被代理的类,所以getGenericSuperclass只是取到被代理类的Type。
    		正常应该是要取到被代理类所继承的父类的Type,
    		所以要先getSuperclass取到被代理类再getGenericSuperclass取到父类的Type才成*/

    	/*Type type = getClass().getGenericSuperclass();
    	if(!(type instanceof ParameterizedType)){
    	    type = getClass().getSuperclass().getGenericSuperclass();
    	}
    	entityClass = (Class<T>)((ParameterizedType)type).getActualTypeArguments()[0];*/
    }
    
	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}	
	public void closeSession(){
		HibernateSessionFactory.closeSession();
	}

	@Override
	public void save(T instance) {
		log.debug("saving "+instance+" instance");
		Transaction tx = getSession().beginTransaction();
		try {
			getSession().save(instance);
			tx.commit();
			log.debug("save successful");
		} catch (RuntimeException re) {
			tx.rollback();
			log.error("save failed", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	@Override
	public void delete(T instance) {
		log.debug("deleting "+instance+" instance");
		Transaction tx = getSession().beginTransaction();
		try {
			getSession().delete(instance);
			tx.commit();
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	@Override
	public void update(T instance) {
		log.debug("updating "+instance+" instance");
		Transaction tx = getSession().beginTransaction();
		try {
			getSession().update(instance);
			tx.commit();
			log.debug("update successful");
		} catch (RuntimeException re) {
			tx.rollback();
			log.error("update failed", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public Object findById(Class clazz, Integer id) {
		log.debug("getting "+clazz+" instance with id: " + id);
		try {
			//Hibernate.initialize(District.class);
			Object o = getSession().get(clazz,id);
			return o;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll() {
		log.debug("getting "+entityClass+" List All ");
		try {
			String hql = "FROM "+entityClass;
			Query queryObject = getSession().createQuery(hql);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by HQL ", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	/**
	 * 根据class类查询数据
	 * @param class
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List findAll(Class clazz) {
		log.debug("getting "+clazz+" List All ");
		try {
			String c = clazz.toString();
			String hql = "FROM "+c.substring(c.lastIndexOf(".")+1,c.length());
			Query queryObject = getSession().createQuery(hql);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by HQL ", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	/**
	 * 根据对象名和对象属性查询数据
	 * @param className
	 * @param propertyName
	 * @param value
	 * @return 实体对象列表
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByProperty(String className,String propertyName, Object value) {
		log.debug("finding "+className+" instance with property: " + propertyName + ", value: " + value);
		
		try {
			String hql = "FROM "+className+" as o WHERE o."+propertyName+" = ?";
			Query queryObject = getSession().createQuery(hql);
			queryObject.setParameter(0, value);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	/**
	 * 根据HQL查询数据
	 * @param hql
	 * @return 实体对象列表
	 */
	@SuppressWarnings("rawtypes")
	public List findByHql(String hql) {
		log.debug(hql);
		try {
			Query queryObject = getSession().createQuery(hql);
			
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by HQL ", re);
			throw re;
		} finally{
			closeSession();
		}
	}
	
	/**
	 * 方案一、获取分页对象,实现分页获取数据的功能
	 * @param hql 查询数据的HQL
	 * @param page 需要显示数据的页码
	 * @param pageSize 每页数据量
	 * @return Object[0]当前页的数据列表List ,Object[1]总页数,Object[2]总数量
	 */
	@SuppressWarnings("rawtypes")
	public Object[] findPageByHql(final String hql, String hqlCount, final int page, final int pageSize) {
		log.debug(hql);
		List list = new ArrayList();
		//总记录数
		Long total = new Long(0);
		//总页数
		Integer totalPage = 0;
		try {
			//1、根据hql语句查询指定数据
			Query qList = getSession().createQuery(hql);
			qList.setFirstResult(page * pageSize);
			qList.setMaxResults(pageSize);
		    list = qList.list();
		    
			//2、根据hql语句查询总记录数
		    List listCount = findByHql(hqlCount);
			if(listCount!=null && listCount.size()>0){
				total = (Long)listCount.get(0);
			}
			
			//3、根据总记录数计算出总页数,ceil进1
			totalPage = (int) Math.ceil((double) total.longValue() / pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeSession();
		}
		
		return new Object[] { list, totalPage, total };
	}
	
	/**
	 * 方案二、通过分页对象,实现分页获取数据的功能
	 * @param hql 查询数据的HQL
	 * @param page 分页对象
	 * @return page 分页对象
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Page findPageByHql(final String hql, String hqlCount, Page page) {
		log.debug(hql);
		try {
			if(page != null){
				//1、根据hql语句查询指定数据
				Query qList = getSession().createQuery(hql);
				qList.setFirstResult(page.getStartRow());
				qList.setMaxResults(page.getSize());
			    page.setList(qList.list());//将数据集合保存到page对象
			    
				//2、根据hql语句查询总记录数
			    List listCount = findByHql(hqlCount);
				if(listCount!=null && listCount.size()>0){
					page.setTotalCount(Integer.parseInt(String.valueOf(listCount.get(0))));//将总记录数保存到page对象
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeSession();
		}
	
		return page;
	}
}

 

------------------------------

public class BaseDaoImpl<T>{  
  
    // 保存当前运行类的参数化类型中的实际的类型  
    private Class clazz;  
    // 表名  
    private String tableName;  
    // 构造函数: 1. 获取当前运行类的参数化类型; 2. 获取参数化类型中实际类型的定义(class)  
    public BaseDaoImpl(){  
        //  this  表示当前运行类  (假设是AccountDao或AdminDao)  
        //  this.getClass()  当前运行类的字节码(AccountDao.class或AdminDao.class)  
        //  this.getClass().getGenericSuperclass();  当前运行类的父类,即为BaseDaoImpl<Account>  
        //                                           其实就是“参数化类型”, ParameterizedType     
        Type type = this.getClass().getGenericSuperclass();  
        // 强制转换为“参数化类型”  【BaseDaoImpl<Account>】  
        ParameterizedType pt = (ParameterizedType) type;  
        // 获取参数化类型中,实际类型的定义  【new Type[]{Account.class}】  
        Type types[] =  pt.getActualTypeArguments();  
        // 获取数据的第一个元素:Accout.class  
        clazz = (Class) types[0];  
        // 表名  (与类名一样,只要获取类名就可以)  
        tableName = clazz.getSimpleName();  
    }  

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics