`
zkgale
  • 浏览: 99871 次
  • 性别: Icon_minigender_1
  • 来自: 成都
文章分类
社区版块
存档分类
最新评论

这段代码能否做成通用DAO???

阅读更多
前段时间在学习Hibernate,今天正式开始用,在用的过程中我为每个表(对象)做了一个DAO,主要用来实现增删改查,因为里面的很多的表(对象)需要写很多DAO,所以我就抽象了一个类,先前也没觉得怎么,不过到后来觉得我抽象出来的这个东西好象能通用吧... ...
现在拿出来让大家看看我这样抽象是否正确,是否对大家有点帮助...同时也希望它能完善...
自己只是简单的测了一下下

package com.st.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.st.hibernate.HibernateSessionFactory;


public abstract class abstractDAO
{
	private Object obj;
//	实现增加,删除,修改的功能
	public boolean idu(char t)
	{
		if(this.obj!=null)
		{
			Session session=HibernateSessionFactory.getSession();
			Transaction ts=session.beginTransaction();
			switch (t)
			{
			case 'i':
				insert(this.obj,session);
				break;
			case 'd':
				delete(this.obj,session);
				break;
			case 'u':
				update(this.obj,session);
				break;
			}	
			ts.commit();
			session.close();
			return true;
		}
		return false;
	}
	//查询
	public List select(char t)
	{
		Session session=HibernateSessionFactory.getSession();
		Transaction ts=session.beginTransaction();
		List list=null;
		switch (t)
		{
		case 'f':
			list=selectFactor(this.obj,session);
			break;
		case 'a':
			list=selectAll(session);
			break;
		}	
		ts.commit();
		session.close();
		return list;
	}
	//删除
	private void delete(Object obj,Session session)
	{
		session.delete(obj);
	}
	//更新
	private void update(Object obj,Session session)
	{
		session.update(obj);
	}
	//添加
	private void insert(Object obj,Session session)
	{
		session.save(obj);
	}
	//查询出所有的记录
	private List selectAll(Session session)
	{		
		Criteria criteria=session.createCriteria(this.obj.getClass());
		return criteria.list();
	}
	//查询,这个查询主要是用来进行模糊查询,或有条件的查询
	protected abstract List selectFactor(Object obj,Session session);
//	{
//		if(p!=null)
//		{
//			Products tempp=null;
////			Query qu=session.createQuery("from Products");
//			Criteria criteria=session.createCriteria(Products.class);
//			//得到一个Products的克隆版本
//			try
//			{
//				tempp=(Products) p.clone();
//			} catch (CloneNotSupportedException e)
//			{
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			criteria.add(Example.create(tempp));
//			if(this.products.getName()!=null && !this.products.getName().equals(""))
//				criteria.add(Restrictions.like("name", "%"+p.getName()+"%"));
//			return criteria.list();
//		}
//		else
//			return null;
//	}
	

	public Object getObj()
	{
		return obj;
	}
	public void setObj(Object obj)
	{
		this.obj = obj;
	}
	
}

分享到:
评论
25 楼 slaser 2008-08-07  
其实有了hibernate,dao还有什么用?
24 楼 kjj 2008-08-06  
以前就是由于这种写法粘连性太强,为了清晰解耦才把方法清晰划分出来,你这 ....... 唉,我都不好意思说什么了,如果你才学习的话倒也情有可原.......
23 楼 CALM 2008-08-05  
魔力猫咪 写道
public boolean idu(char t)这个方法严重有问题。为什么要把增删改用这个间接实现?查询方法也一样。头一次看见这么写的。而且方法传入的那几个char也没有做静态属性,别人不知道你源代码的情况下谁知道应该往里头传什么。增删改方法如果一个请求内多次调用,每次都要提交一次,等于实际上没有事务控制。如果中间操作出错,事务原子性根本无法保证。建议你去看看Spring的HibernateSupper

这是什么?
22 楼 liuxin0448 2008-04-17  
请问各位大侠
Constants.MAXRESULT
是那个包下的Class
在这里又起什么作用呢~!
21 楼 spiritfrog 2008-04-13  
魔力猫咪 写道
引用
至于public int executeUpdate(final String hql)这个还请你举个例子说明一下。
主要是你传入了HQL语句。HQL是Hibernate专有的语言,别的框架不支持这种语言。虽然JPA的查询语言和HQL基本差不多,但是还有可能在某些地方不一样。所以你这个方法就变成了只能Hibernate使用的专用方法。Service的使用者也就必须知道底层实现是Hibernate。造成了应用和持久化的紧耦合。
还有就是Update和Delete操作语句要小心,如果使用了Hibernate的二级缓存和查询缓存,那么Update和Delete使用的时候,必须清理缓存。你这里并没有缓存清理操作。除非你绝对不使用二级缓存,不然这么做是会出问题的。
我们封装的时候,对这些方面要考虑清楚。

public int executeUpdate(final String hql);对于这种方式,我觉得还是没问题的,不会又用hibernate又用jpa的吧;
对于这个方法对二级缓存的影响,确实需要注意。
lz的dao可以考虑用范型的,这样子类dao将明确知道对应的实体类型,返回时候也不必转型了。另外,不要将crud搞成一个方法,反倒迷惑了调用者。
再有lsk的那个通用dao确实挺全的,呵呵。

20 楼 ericxu131 2008-04-12  
应该说范型dao是最好的解决方案了吧。
hibernate官网上有的。
19 楼 smallboy2008 2008-04-12  
348105874 写道
c,,u,d等方法最好不要混在一起

这点我同意
可以防止混乱
18 楼 melin 2008-04-11  
在liferay中大部分增删改的action是相同的,通过常量来判断Constants.CMD。来判断执行什么操作,service也类似。
17 楼 flustar 2008-04-11  
这个是我写的泛型dao
看看对你是否有帮助
http://www.blogjava.net/flustar/archive/2007/12/26/ssha.html
16 楼 hysoft 2008-04-11  
DAO 不参杂业务 只管数据操作

事务啥的放在service
15 楼 terranhao 2008-04-11  
不好意思,我从来都是直接用hibernate的语句增删改
我想问的是这种DAO方法到底好在哪里,他一条语句delete
我用session一样是一个delete,这种方法哪里好了?
我真的从来没用过DAO,请大家指教
14 楼 魔力猫咪 2008-04-09  
引用
至于public int executeUpdate(final String hql)这个还请你举个例子说明一下。
主要是你传入了HQL语句。HQL是Hibernate专有的语言,别的框架不支持这种语言。虽然JPA的查询语言和HQL基本差不多,但是还有可能在某些地方不一样。所以你这个方法就变成了只能Hibernate使用的专用方法。Service的使用者也就必须知道底层实现是Hibernate。造成了应用和持久化的紧耦合。
还有就是Update和Delete操作语句要小心,如果使用了Hibernate的二级缓存和查询缓存,那么Update和Delete使用的时候,必须清理缓存。你这里并没有缓存清理操作。除非你绝对不使用二级缓存,不然这么做是会出问题的。
我们封装的时候,对这些方面要考虑清楚。封装的方法不合适,不但不能很好解藕,反而给变成带来了麻烦。
我看到过一个Hibernate封装。好像是因为怕别人不会用Hibernate,在Dao里把Hibernate全给封起来了。连Session也拿不出来。但是传入的参数都是Hibernate专有的HQL语句。你说这算什么封装。最后弄得大家都不好干。
13 楼 Joo 2008-04-09  
jolestar 写道
恩。不用范型类型转换太麻烦,用范型,基本就需要一个DAO,别的具体操作可以方在Service层里。


意思整个DAO层就一个DAO类就可以了
涉及到具体的不同类型查询操作一般写哪里?我原来的做法是每个EntityBean对应一个EntityDAO,有关她的持久层操作都在这里面,然后让他extends一个BaseDAO
12 楼 xzy_del 2008-04-09  
import java.io.Serializable;
public interface GenericDao<T,PK extends Serializable> {

PK create(T newInstance);

T read(PK id);

void update(T transientObject);

void delete(T persistentObject);
}
可以试试用泛型
11 楼 SoldierBandit 2008-04-09  
每个公司都不一样吧!像我们公司,就不用数据库的框架!呵呵
10 楼 lsk 2008-04-08  
魔力猫咪 写道

使用了Spring的Hibernate支持,怎么不用Spring的声明式事务管理?private Serializable save(Session session, Object p) 方法居然自己控制事务。但是其他方法又没有事务。到底事务控制是方应用层控制还是扔DAO里了?
还有public Serializable save2(final Object entity) throws DataAccessException 命名不科学。没人知道save2是什么意思。public int executeUpdate(final String hql)暴露了DAO实现,没有把领域层和持久化层隔离。而且这个方法会造成缓存失效,没有清理缓存的语句。


阁下果然眼明。 事务是在service层控制的.dao没有,至于哪个private Serializable save 和save2是是当初写这个dao的人加的。地层代码一般最好还是不要动。
至于public int executeUpdate(final String hql)这个还请你举个例子说明一下。
9 楼 jolestar 2008-04-08  
恩。不用范型类型转换太麻烦,用范型,基本就需要一个DAO,别的具体操作可以方在Service层里。
8 楼 star022 2008-04-08  
movingboy 写道
建议楼主搜索一下“泛型DAO”,或许会有收获

我做的项目重中,
就为公司写了一个泛型DAO,
所有表或者视图的基本操作全封装在里面了。
7 楼 魔力猫咪 2008-04-08  
lsk 写道
帖一段我们的baseDao给你看看
public class BaseDaoHibernate extends HibernateDaoSupport implements BaseDao {

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

	public void save(final Object obj) {
		getHibernateTemplate().save(obj);
		// save2(obj);
	}

	private Serializable save(Session session, Object p) {
		Transaction t = session.beginTransaction();
		Serializable o = session.save(p);
		t.commit();
		session.flush();
		session.close();
		return o;
	}

	public Serializable save2(final Object entity) throws DataAccessException {
		Object o = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				return save(session, entity);
			}
		});
		return null;
	}

	public void deleteAll(final Object o) {
		String hql = "   delete from  " + o.getClass().getName() + "  ";
		executeUpdate(hql);
	}

	/**
	 * 根据查询语句,返回对象列表
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List find(final String hql) {
		final int firstResult = 0;
		return find(hql, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 根据查询语句,返回对象列表
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List find(final String hql, List tablesName) {
		final int firstResult = 0;
		return find(hql, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 返回指定起始位置,指定条数的对象
	 * 
	 * @param hql
	 *            查询语句
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List find(final String hql, final int firstResult,
			final int maxResults) {
		if (log.isDebugEnabled()) {
			log.debug("hql=" + hql);
		}
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				try {
					session.connection().setReadOnly(true);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Query queryObject = session.createQuery(hql);
				queryObject.setReadOnly(true);
				queryObject.setFirstResult(firstResult);
				queryObject.setMaxResults(maxResults);
				return queryObject.list();
			}
		});
	}

	/**
	 * 返回指定起始位置,指定条数的对象
	 * 
	 * @param hql
	 *            查询语句
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List findByIterate(final String hql) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				Query queryObject = session.createQuery(hql);
				queryObject.setCacheable(true);
				Iterator iter = queryObject.iterate();
				List ls = new ArrayList();
				while (iter.hasNext()) {
					ls.add(iter.next());
				}
				return ls;
			}
		});
	}

	/**
	 * 查询语句需要的条件参数。通过map传递
	 * 
	 * @param hql
	 *            查询语句
	 * @param map
	 *            参数
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List find(final String hql, final Map map, final int firstResult,
			final int maxResults) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				Query queryObject = session.createQuery(hql);
				String[] params = queryObject.getNamedParameters();
				for (int i = 0, max = params.length; i < max; i++) {
					queryObject.setParameter(params[i], map.get(params[i]));
				}
				queryObject.setFirstResult(firstResult);
				queryObject.setMaxResults(maxResults);
				return queryObject.list();
			}
		});
	}

	/**
	 * 根据查询语句,返回对象列表
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List find(final String hql, final Map map) {
		final int firstResult = 0;
		return find(hql, map, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 通过Hql 执行update/delete操作
	 * 
	 * @param hql
	 * @return
	 */
	public int executeUpdate(final String hql) {
		int result = 0;
		Object o = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				int result = 0;
				Query queryObject = session.createQuery(hql);

				result = queryObject.executeUpdate();
				return result;

			}
		});
		Integer i = (Integer) o;
		result = i.intValue();
		return result;
	}

	public void deleteAllByObject(Object obj) {
		List l = null;
		String hql = "   from  " + obj.getClass().getName() + "  ";
		if (log.isDebugEnabled()) {
			log.debug("hql=" + hql);
		}
		l = find(hql);
		Iterator ait = l.iterator();
		while (ait != null && ait.hasNext()) {
			getHibernateTemplate().delete(ait.next());
		}
	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteria(final DetachedCriteria dc) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				return criteria.list();
			}
		}, true);

	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteria(final DetachedCriteria dc,
			final int firstResult, final int maxResults) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("findByCriteria dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				criteria.setFirstResult(firstResult);
				criteria.setMaxResults(maxResults);
				return criteria.list();
			}
		}, true);

	}

	public int countByCriteria(final DetachedCriteria dc) {
		Integer count = (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						if (log.isDebugEnabled()) {
							log.debug("countByCriteria dc=" + dc);
						}
						Criteria criteria = dc.getExecutableCriteria(session);
						return criteria.setProjection(Projections.rowCount())
								.uniqueResult();
					}
				}, true);
		if (count != null) {
			return count.intValue();
		} else {
			return 0;
		}
	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteriaCache(final DetachedCriteria dc) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				criteria.setCacheable(true);
				return criteria.list();
			}
		}, true);

	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteriaCache(final DetachedCriteria dc,
			final int firstResult, final int maxResults) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				criteria.setCacheable(true);
				criteria.setFirstResult(firstResult);
				criteria.setMaxResults(maxResults);
				return criteria.list();
			}
		}, true);

	}

	/**
	 * count search cache
	 */
	public int countByCriteriaCache(final DetachedCriteria dc) {
		Integer count = (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						if (log.isDebugEnabled()) {
							log.debug("dc=" + dc);
						}
						Criteria criteria = dc.getExecutableCriteria(session);
						criteria.setCacheable(true);
						return criteria.setProjection(Projections.rowCount())
								.uniqueResult();
					}
				}, true);
		if (count != null) {
			return count.intValue();
		} else {
			return 0;
		}
	}

	public int executeUpdate(final String hql, final Map pMap) {
		int result = 0;
		Object o = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				int result = 0;
				Query queryObject = session.createQuery(hql);
				String[] params = queryObject.getNamedParameters();
				for (int i = 0, max = params.length; i < max; i++) {
					queryObject.setParameter(params[i], pMap.get(params[i]));
				}
				result = queryObject.executeUpdate();
				return result;

			}
		});
		Integer i = (Integer) o;
		result = i.intValue();
		return result;
	}

	public void delete(Object obj) {
		getHibernateTemplate().delete(obj);
	}

	public Object load(Class aclass, Serializable id)
			throws DataAccessException {
		Object obj = getHibernateTemplate().load(aclass, id);
		return obj;
	}

	public Object get(Class aclass, Serializable id) {
		Object obj = getHibernateTemplate().get(aclass, id);
		return obj;
	}

	public void saveorUpdate(Object obj) {
		getHibernateTemplate().saveOrUpdate(obj);
		getHibernateTemplate().flush();
	}

	public void update(Object o) {
		getHibernateTemplate().update(o);
	}

	/**
	 * count hql 方法 .
	 */
	public int count(String hql, List ls) {
		String countQueryString = " select count (*) " + hql;
		List countlist = getHibernateTemplate().find(countQueryString);
		Long count = (Long) countlist.get(0);
		return count.intValue();
	}

	/**
	 * count hql 方法 .
	 */
	public int count(String hql, Map params) {
		String countQueryString = " select count (*) " + hql;
		List countlist = find(countQueryString, params);
		Object co = countlist.get(0);
		if (co instanceof Integer) {
			Integer count = (Integer) countlist.get(0);
			return count.intValue();
		} else {
			Long count = (Long) countlist.get(0);
			return count.intValue();
		}
	}

	/**
	 * TODO count hql 方法 .
	 */
	public int countCache(String hql, Map params) {
		String countQueryString = " select count (*) " + hql;
		List countlist = findCache(countQueryString, params);
		Object co = countlist.get(0);
		if (co instanceof Integer) {
			Integer count = (Integer) countlist.get(0);
			return count.intValue();
		} else {
			Long count = (Long) countlist.get(0);
			return count.intValue();
		}
	}

	/**
	 * 根据查询语句,返回对象列表 TODO
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List findCache(final String hql, final Map map) {
		final int firstResult = 0;
		return findCache(hql, map, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 查询语句需要的条件参数。通过map传递 TODO
	 * 
	 * @param hql
	 *            查询语句
	 * @param map
	 *            参数
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List findCache(final String hql, final Map map,
			final int firstResult, final int maxResults) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				Query queryObject = session.createQuery(hql);
				// 设置 查询cache
				queryObject.setCacheable(true);
				String[] params = queryObject.getNamedParameters();
				for (int i = 0, max = params.length; i < max; i++) {
					queryObject.setParameter(params[i], map.get(params[i]));
				}
				queryObject.setFirstResult(firstResult);
				queryObject.setMaxResults(maxResults);
				return queryObject.list();
			}
		});
	}

	public int count(String hql) {
		String countQueryString = " select count (*) " + hql;
		List countlist = find(countQueryString);
		Object co = countlist.get(0);
		if (co instanceof Integer) {
			Integer count = (Integer) countlist.get(0);
			return count.intValue();
		} else {
			Long count = (Long) countlist.get(0);
			return count.intValue();
		}
	}

	@Override
	public HibernateTemplate getTemplate() {
		return getHibernateTemplate();
	}


使用了Spring的Hibernate支持,怎么不用Spring的声明式事务管理?private Serializable save(Session session, Object p) 方法居然自己控制事务。但是其他方法又没有事务。到底事务控制是方应用层控制还是扔DAO里了?
还有public Serializable save2(final Object entity) throws DataAccessException 命名不科学。没人知道save2是什么意思。public int executeUpdate(final String hql)暴露了DAO实现,没有把领域层和持久化层隔离。而且这个方法会造成缓存失效,没有清理缓存的语句。
6 楼 lsk 2008-04-08  
帖一段我们的baseDao给你看看
public class BaseDaoHibernate extends HibernateDaoSupport implements BaseDao {

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

	public void save(final Object obj) {
		getHibernateTemplate().save(obj);
		// save2(obj);
	}

	private Serializable save(Session session, Object p) {
		Transaction t = session.beginTransaction();
		Serializable o = session.save(p);
		t.commit();
		session.flush();
		session.close();
		return o;
	}

	public Serializable save2(final Object entity) throws DataAccessException {
		Object o = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				return save(session, entity);
			}
		});
		return null;
	}

	public void deleteAll(final Object o) {
		String hql = "   delete from  " + o.getClass().getName() + "  ";
		executeUpdate(hql);
	}

	/**
	 * 根据查询语句,返回对象列表
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List find(final String hql) {
		final int firstResult = 0;
		return find(hql, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 根据查询语句,返回对象列表
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List find(final String hql, List tablesName) {
		final int firstResult = 0;
		return find(hql, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 返回指定起始位置,指定条数的对象
	 * 
	 * @param hql
	 *            查询语句
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List find(final String hql, final int firstResult,
			final int maxResults) {
		if (log.isDebugEnabled()) {
			log.debug("hql=" + hql);
		}
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				try {
					session.connection().setReadOnly(true);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Query queryObject = session.createQuery(hql);
				queryObject.setReadOnly(true);
				queryObject.setFirstResult(firstResult);
				queryObject.setMaxResults(maxResults);
				return queryObject.list();
			}
		});
	}

	/**
	 * 返回指定起始位置,指定条数的对象
	 * 
	 * @param hql
	 *            查询语句
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List findByIterate(final String hql) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				Query queryObject = session.createQuery(hql);
				queryObject.setCacheable(true);
				Iterator iter = queryObject.iterate();
				List ls = new ArrayList();
				while (iter.hasNext()) {
					ls.add(iter.next());
				}
				return ls;
			}
		});
	}

	/**
	 * 查询语句需要的条件参数。通过map传递
	 * 
	 * @param hql
	 *            查询语句
	 * @param map
	 *            参数
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List find(final String hql, final Map map, final int firstResult,
			final int maxResults) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				Query queryObject = session.createQuery(hql);
				String[] params = queryObject.getNamedParameters();
				for (int i = 0, max = params.length; i < max; i++) {
					queryObject.setParameter(params[i], map.get(params[i]));
				}
				queryObject.setFirstResult(firstResult);
				queryObject.setMaxResults(maxResults);
				return queryObject.list();
			}
		});
	}

	/**
	 * 根据查询语句,返回对象列表
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List find(final String hql, final Map map) {
		final int firstResult = 0;
		return find(hql, map, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 通过Hql 执行update/delete操作
	 * 
	 * @param hql
	 * @return
	 */
	public int executeUpdate(final String hql) {
		int result = 0;
		Object o = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				int result = 0;
				Query queryObject = session.createQuery(hql);

				result = queryObject.executeUpdate();
				return result;

			}
		});
		Integer i = (Integer) o;
		result = i.intValue();
		return result;
	}

	public void deleteAllByObject(Object obj) {
		List l = null;
		String hql = "   from  " + obj.getClass().getName() + "  ";
		if (log.isDebugEnabled()) {
			log.debug("hql=" + hql);
		}
		l = find(hql);
		Iterator ait = l.iterator();
		while (ait != null && ait.hasNext()) {
			getHibernateTemplate().delete(ait.next());
		}
	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteria(final DetachedCriteria dc) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				return criteria.list();
			}
		}, true);

	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteria(final DetachedCriteria dc,
			final int firstResult, final int maxResults) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("findByCriteria dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				criteria.setFirstResult(firstResult);
				criteria.setMaxResults(maxResults);
				return criteria.list();
			}
		}, true);

	}

	public int countByCriteria(final DetachedCriteria dc) {
		Integer count = (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						if (log.isDebugEnabled()) {
							log.debug("countByCriteria dc=" + dc);
						}
						Criteria criteria = dc.getExecutableCriteria(session);
						return criteria.setProjection(Projections.rowCount())
								.uniqueResult();
					}
				}, true);
		if (count != null) {
			return count.intValue();
		} else {
			return 0;
		}
	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteriaCache(final DetachedCriteria dc) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				criteria.setCacheable(true);
				return criteria.list();
			}
		}, true);

	}

	/**
	 * 通过 DetachedCriteria 进行查询
	 * 
	 * @param dc
	 * @return
	 */
	public List findByCriteriaCache(final DetachedCriteria dc,
			final int firstResult, final int maxResults) {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				if (log.isDebugEnabled()) {
					log.debug("dc=" + dc);
				}
				Criteria criteria = dc.getExecutableCriteria(session);
				criteria.setCacheable(true);
				criteria.setFirstResult(firstResult);
				criteria.setMaxResults(maxResults);
				return criteria.list();
			}
		}, true);

	}

	/**
	 * count search cache
	 */
	public int countByCriteriaCache(final DetachedCriteria dc) {
		Integer count = (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						if (log.isDebugEnabled()) {
							log.debug("dc=" + dc);
						}
						Criteria criteria = dc.getExecutableCriteria(session);
						criteria.setCacheable(true);
						return criteria.setProjection(Projections.rowCount())
								.uniqueResult();
					}
				}, true);
		if (count != null) {
			return count.intValue();
		} else {
			return 0;
		}
	}

	public int executeUpdate(final String hql, final Map pMap) {
		int result = 0;
		Object o = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				int result = 0;
				Query queryObject = session.createQuery(hql);
				String[] params = queryObject.getNamedParameters();
				for (int i = 0, max = params.length; i < max; i++) {
					queryObject.setParameter(params[i], pMap.get(params[i]));
				}
				result = queryObject.executeUpdate();
				return result;

			}
		});
		Integer i = (Integer) o;
		result = i.intValue();
		return result;
	}

	public void delete(Object obj) {
		getHibernateTemplate().delete(obj);
	}

	public Object load(Class aclass, Serializable id)
			throws DataAccessException {
		Object obj = getHibernateTemplate().load(aclass, id);
		return obj;
	}

	public Object get(Class aclass, Serializable id) {
		Object obj = getHibernateTemplate().get(aclass, id);
		return obj;
	}

	public void saveorUpdate(Object obj) {
		getHibernateTemplate().saveOrUpdate(obj);
		getHibernateTemplate().flush();
	}

	public void update(Object o) {
		getHibernateTemplate().update(o);
	}

	/**
	 * count hql 方法 .
	 */
	public int count(String hql, List ls) {
		String countQueryString = " select count (*) " + hql;
		List countlist = getHibernateTemplate().find(countQueryString);
		Long count = (Long) countlist.get(0);
		return count.intValue();
	}

	/**
	 * count hql 方法 .
	 */
	public int count(String hql, Map params) {
		String countQueryString = " select count (*) " + hql;
		List countlist = find(countQueryString, params);
		Object co = countlist.get(0);
		if (co instanceof Integer) {
			Integer count = (Integer) countlist.get(0);
			return count.intValue();
		} else {
			Long count = (Long) countlist.get(0);
			return count.intValue();
		}
	}

	/**
	 * TODO count hql 方法 .
	 */
	public int countCache(String hql, Map params) {
		String countQueryString = " select count (*) " + hql;
		List countlist = findCache(countQueryString, params);
		Object co = countlist.get(0);
		if (co instanceof Integer) {
			Integer count = (Integer) countlist.get(0);
			return count.intValue();
		} else {
			Long count = (Long) countlist.get(0);
			return count.intValue();
		}
	}

	/**
	 * 根据查询语句,返回对象列表 TODO
	 * 
	 * @param hql
	 *            查询语句
	 * @return 符合查询语句的对象列表;最多返回 Constants.maxResults 条
	 */
	public List findCache(final String hql, final Map map) {
		final int firstResult = 0;
		return findCache(hql, map, firstResult, Constants.MAXRESULTS);
	}

	/**
	 * 查询语句需要的条件参数。通过map传递 TODO
	 * 
	 * @param hql
	 *            查询语句
	 * @param map
	 *            参数
	 * @param firstResult
	 *            起始位置
	 * @param maxResults
	 *            最多纪录数
	 * @return list 结果列表
	 */
	public List findCache(final String hql, final Map map,
			final int firstResult, final int maxResults) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException {
				Query queryObject = session.createQuery(hql);
				// 设置 查询cache
				queryObject.setCacheable(true);
				String[] params = queryObject.getNamedParameters();
				for (int i = 0, max = params.length; i < max; i++) {
					queryObject.setParameter(params[i], map.get(params[i]));
				}
				queryObject.setFirstResult(firstResult);
				queryObject.setMaxResults(maxResults);
				return queryObject.list();
			}
		});
	}

	public int count(String hql) {
		String countQueryString = " select count (*) " + hql;
		List countlist = find(countQueryString);
		Object co = countlist.get(0);
		if (co instanceof Integer) {
			Integer count = (Integer) countlist.get(0);
			return count.intValue();
		} else {
			Long count = (Long) countlist.get(0);
			return count.intValue();
		}
	}

	@Override
	public HibernateTemplate getTemplate() {
		return getHibernateTemplate();
	}

相关推荐

    泛型通用DAO,可以很简化DAO层的代码

    自己写的泛型通用DAO,可以很简化DAO层的代码,但是目前只能支持单表的增,删,查,改。可以充分的理解jdk5.0的泛型和反射机制。希望大家指正不足之处!

    C#特性标签实现通用Dao层

    C#特性标签实现通用Dao层C#特性标签实现通用Dao层C#特性标签实现通用Dao层

    Java源代码一个简单的通用DAO实现(基于hibernate)

    Java源代码 一个简单的通用DAO实现 (基于hibernate)面向应用层按POJO类缓存hibernate的session对象.使用举例: DAO dao = DAOFactory.getDAO(POJO.class);//获得一个全局类单例的DAO实例 dao.save(pojo); 你也可以...

    java ssh通用DAO另类实现示例

    java ssh通用DAO另类实现示例 java ssh通用DAO另类实现示例

    java 基于泛型与反射的通用 DAO

    java的基于泛型+反射的通用DAO例子,原创,没事写着玩的,请多指教哈。。。

    高仿JPA自定义通用DAO

    自定义通用DAO实现基本的CRUD,比如: public interface BaseDao&lt;T&gt; { int insert(T obj) throws Exception; int update(T obj) throws Exception; int deleteByPrimaryKey(Object key) throws Exception; int ...

    Hibernate通用Dao

    通用dao,简单全面,所有dao都可以继承这个dao.

    ssm(Spring-springMVC-Mybatis)通用Dao框架

    Spring-springMVC-Mybatis通用Dao框架,附带sql文件,下载导入开发工具可直接运行查看效果

    HibernateDao 通用

    HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao 通用HibernateDao ...

    Hibernate_通用DAO模式,一个写好的dao层

    这个是不同类型的表单通用的dao模式,简洁明了,注释清楚,可移植性很强

    Java通用连接DAO

    Java通用连接DAO有JDBC连接和JNDI 两种,含源代码。

    Mybatis通用Dao

    现在越来越多的开发者使用MyBatis作为ORM的框架,它开发迅速,上手容易,开源代码多...因此本人一直想寻找一个类似hibernate一样的通用数据库管理Dao,采用spring注入的方式即可。现在已创建项目的方式和大家一起分享。

    hibernate spring通用dao

    spring集成hibernate通用dao,泛型,server都可以调用

    Hibernate通用Dao设计。

    NULL 博文链接:https://azure2a.iteye.com/blog/1128097

    泛型dao 泛型dao 泛型dao

    能不能不写重复的dao 呢 ? 泛型dao,顾名思义就是一个dao可以对多个实体对象进行持久化。当应用中需要使用到上十张表时,DAO的维护变得日益困难,主要表现在这几个方面: 1)dao类的繁多,很多设计都是一个...

    基于java泛型的通用DAO(CURD)实现

    现在无论做什么应用,基本上都会有涉及对象持久化这方面的操作。通常创建大量的DAO对象是我们开发过程中最常见的操作了。创建DAO对象的优点主要体现在提高代码复用和降低业务逻辑操作与业务实体持久化之间的耦合。 ...

    一个很好的通用泛型dao(含源码)

    为什么我们要使用通用DAO接口呢,因为我们的数据库操作无非是增删改查,CRUD操作,我们不需要为每个实体去编写一个dao接口,对于相似的实体操作可以只编写一个通用接口,然后采用不同的实现! DAO已经成为持久层...

    通用SSH2结构的标准代码,通用dao实现类serviceImpl实现类

    通用SSH2结构的增删查改标准代码, bean,HBM文件为自定义, service,dao接口为标准可重用 servce实现,dao实现为通用 -----使用说明--- action 调用通用service,service调用通用dao 调用关系用spring 配址文件设置 ...

    hibernate4 通用dao,service

    NULL 博文链接:https://peak1992.iteye.com/blog/2356992

    7.DAO数据库表字段操作演示(Visual C++编程 源代码)

    7.DAO数据库表字段操作演示(Visual C++编程 源代码)7.DAO数据库表字段操作演示(Visual C++编程 源代码)7.DAO数据库表字段操作演示(Visual C++编程 源代码)7.DAO数据库表字段操作演示(Visual C++编程 源代码)...

Global site tag (gtag.js) - Google Analytics