dao层封装的方法[ 不使用hibernate的Template模板]

1. 基础DAO接口ICommonDao.java

package cn.itcast.crm.dao;

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

/**
 * 基础DAO
 */
public interface ICommonDao<T> {
	
	// 无排序的条件查询[重载]
	public List<T> findObjectByCondictionWithNoPage(String whereHql,
			Object[] params);
	
	// 根据条件查询排序
	public List<T> findObjectByCondictionWithNoPage(String whereHql,
			Object[] params, LinkedHashMap<String, String> orderby);
	
	// 批量删除对象
	public void deleteAllObjects(Collection<T> entities); 
	
	// 批量删除对象
	public int deleteByIds(Serializable ... ids);
	
	// 根据id查找对象
	public T findObjectById(Serializable id);
	
	// 保存对象
	public void save(T entity);
	
	// 更新对象
	public void update(T entity);
}

2. 基础接口实现类CommonDaoImpl.java

package cn.itcast.crm.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.itcast.crm.dao.ICommonDao;
import cn.itcast.crm.util.GenericClass;

public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T> {
	
	@SuppressWarnings("rawtypes")
	private Class entityClass = GenericClass.getGenericClass(this.getClass());

	// 更新对象
	@Override
	public void update(T entity) {
		this.getHibernateTemplate().update(entity);
	}
	
	// 保存对象
	@Override
	public void save(T entity) {
		this.getHibernateTemplate().save(entity);
	}

	// 采用注解的方式注入sessionFactory
	@Resource(name="sessionFactory")
	public void setSessionFactoryDI(SessionFactory sessionFactory) {
		// 调用父类的setSessionFactory方法注入setSessionFactory, 
		// 这样HibernateTemplate中就有setSessionFactory了, 就可以对数据库进行CRUD操作
		super.setSessionFactory(sessionFactory);
	}

	// 通过id查找对象
	@SuppressWarnings("unchecked")
	@Override
	public T findObjectById(Serializable id) {
		if (id == null) {
			throw new RuntimeException("您要查找的id[ "+id+" ]不能为空");
		}
		
		return (T) this.getHibernateTemplate().get(entityClass, id);
	}
	
	// 批量删除对象
	@Override
	public int deleteByIds(Serializable... ids) {
		int count = 0;	// 删除的个数
		if (ids != null && ids.length > 0) {
			for (Serializable id : ids) {
				Object entity = this.getHibernateTemplate().get(entityClass, id);
				if (entity == null) {
					throw new RuntimeException("您要删除的id[ "+id+" ]不存在!");
				}
				this.getHibernateTemplate().delete(entity);
				count++;
			}
		}
		return count;
	}

	// 批量删除对象
	@Override
	public void deleteAllObjects(Collection<T> entities) {
		this.getHibernateTemplate().deleteAll(entities);
	}

	// 根据条件查询排序
	@SuppressWarnings({ "unchecked" })
	@Override
	public List<T> findObjectByCondictionWithNoPage(String whereHql,
			final Object[] params, LinkedHashMap<String, String> orderby) {
		// 组织hql
		String hql = "SELECT o FROM "+entityClass.getSimpleName()+" o WHERE 1 = 1";
		
		// 拼接hql
		if (StringUtils.isNotBlank(whereHql)) {
			hql += whereHql;
		}
		
		// 组织排序
		String orderbystr = buildOrderbBy(orderby);
		hql += orderbystr;
		
		System.out.println(hql);
		
		final String fhql = hql;
		List<T> list = (List<T>) this.getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(fhql);
				setParams(query, params);
				return query.list();
			}
		});
		
		return list;
	}

	// 设置hql需要的参数
	private void setParams(Query query, Object[] params) {
		if (params != null && params.length > 0) { 
			for (int i=0; i<params.length; i++) {
				query.setParameter(i, params[i]);
			}
		}
	}
	
	// 拼接排序
	private String buildOrderbBy(LinkedHashMap<String, String> orderby) {
		StringBuffer buf = new StringBuffer("");
		if (orderby != null && !orderby.isEmpty()) {
			buf.append(" ORDER BY ");
			for (Map.Entry<String, String> em : orderby.entrySet()) {
				buf.append(em.getKey()+" "+em.getValue()+",");
			}
			// 去掉最后一个逗号
			buf.deleteCharAt(buf.length()-1);
		}
		return buf.toString();
	}

	// 无排序的条件查询
	@Override
	public List<T> findObjectByCondictionWithNoPage(String whereHql,
			Object[] params) {
		return this.findObjectByCondictionWithNoPage(whereHql, params, null);
	}
	
}

  

 

posted @ 2017-05-28 15:25  半生戎马,共话桑麻、  阅读(187)  评论(0)    收藏  举报
levels of contents