hibernate BaseDao

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

/**
 * 基础数据库操作类
 *
 * @author Frank
 *
 */
public interface BaseDAO<T>
{

	/**
	 * 保存一个对象
	 *
	 * @param o
	 * @return the generated identifier or null
	 */
	public Serializable save(T o);

	/**
	 * 删除一个对象
	 *
	 * @param 是否成功
	 */
	public boolean delete(T o);

	/**
	 * 更新一个对象
	 *
	 * @param 是否成功
	 */
	public boolean update(T o);

	/**
	 * 保存或更新对象
	 *
	 * @param 是否成功
	 */
	public boolean saveOrUpdate(T o);

	/**
	 * 查询
	 *
	 * @param hql
	 * @return the result list or null
	 */
	public List<T> find(String hql);

	/**
	 * 查询集合
	 *
	 * @param hql
	 * @param param
	 * @return the result list or null
	 */
	public List<T> find(String hql, Object[] param);

	/**
	 * 查询集合
	 *
	 * @param hql
	 * @param param
	 * @return the result list or null
	 */
	public List<T> find(String hql, List<Object> param);

	/**
	 * 查询集合(带分页)
	 *
	 * @param hql
	 * @param param
	 * @param page
	 *            查询第几页
	 * @param rows
	 *            每页显示几条记录
	 * @return the result list or null
	 */
	public List<T> find(String hql, Object[] param, Integer page, Integer rows);

	/**
	 * 查询集合(带分页)
	 *
	 * @param hql
	 * @param param
	 * @param page
	 * @param rows
	 * @return the result list or null
	 */
	public List<T> find(String hql, List<Object> param, Integer page, Integer rows);

	/**
	 * 获得一个对象
	 *
	 * @param c
	 *            对象类型
	 * @param id
	 * @return Object or null
	 */
	public T get(Class<T> c, Serializable id);

	/**
	 * 获得一个对象
	 *
	 * @param hql
	 * @param param
	 * @return Object or null
	 */
	public T get(String hql, Object[] param);

	/**
	 * 获得一个对象
	 *
	 * @param hql
	 * @param param
	 * @return Object or null
	 */
	public T get(String hql, List<Object> param);

	/**
	 * select count(*) from 类
	 *
	 * @param hql
	 * @return return a single instance that matches
	 * the query, or null if the query returns no results.
	 */
	public Long count(String hql);

	/**
	 * "select count(*) from 类 where 字段 = ?", new Object[]
		{ 字段的值 }
	 *
	 * @param hql
	 * @param param
	 * @return return a single instance that matches
	 * the query, or null if the query returns no results.
	 */
	public Long count(String hql, Object[] param);

	/**
	 * List<Object> objects = new ArrayList<Object>();
		objects.add("男");
	 * "select count(*) from Customer where sex = ?", objects
	 *
	 * @param hql
	 * @param param
	 * @return return a single instance that matches
	 * the query, or null if the query returns no results.
	 */
	public Long count(String hql, List<Object> param);

	/**
	 * 执行HQL语句
	 *
	 * @param hql
	 * @return The number of entities updated or deleted
	 */
	public Integer executeHql(String hql);

	/**
	 * 执行HQL语句
	 *
	 * @param hql
	 * @param param
	 * @return The number of entities updated or deleted
	 */
	public Integer executeHql(String hql, Object[] param);

	/**
	 * 执行HQL语句
	 *
	 * @param hql
	 * @param param
	 * @return The number of entities updated or deleted
	 */
	public Integer executeHql(String hql, List<Object> param);

}

import java.io.Serializable;
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.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.doshr.xmen.server.dao.BaseDAO;

@SuppressWarnings("all")
public class BaseDAOImpl<T> implements BaseDAO<T>
{
	private static final Log log = LogFactory.getLog(BaseDAOImpl.class);// 获取log实例

	private SessionFactory sessionFactory;
	private HibernateTemplate hibernateTemplate;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	public HibernateTemplate getHibernateTemplate()
	{
		return hibernateTemplate;
	}

	@Autowired
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate)
	{
		this.hibernateTemplate = hibernateTemplate;
	}

	private Session getCurrentSession()
	{
		return sessionFactory.getCurrentSession();
	}

	public Serializable save(T o)
	{
		// 1.参数检查
		if (o != null && hibernateTemplate != null)
		{
			// 2. 保存
			try
			{
				return hibernateTemplate.save(o);
			}
			catch (Exception e)
			{
				log.error("save" + e);
			}
		}
		return null;
	}

	public boolean delete(T o)
	{
		boolean flag = false;
		// 1.参数检查
		if (o != null && hibernateTemplate != null)
		{
			// 2. 删除
			try
			{
				hibernateTemplate.delete(o);
				flag = true;
			}
			catch (Exception e)
			{
				log.error("delete" + e);
				flag = false;
			}
		}
		return flag;
	}

	public boolean update(T o)
	{
		boolean flag = false;
		// 1.参数检查
		if (o != null && hibernateTemplate != null)
		{
			// 2. 更新
			try
			{
				hibernateTemplate.update(o);
				flag = true;
			}
			catch (Exception e)
			{
				log.error("update" + e);
				flag = false;
			}
		}
		return flag;
	}

	public boolean saveOrUpdate(T o)
	{
		boolean flag = false;
		// 1.参数检查
		if (o != null && hibernateTemplate != null)
		{
			// 2. 保存or更新
			try
			{
				hibernateTemplate.saveOrUpdate(o);
				flag = true;
			}
			catch (Exception e)
			{
				log.error("savaOrUpdate" + e);
				flag = false;
			}
		}
		return flag;
	}

	public List<T> find(String hql)
	{
		// 1.非空验证
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				// 2.查找并返回集合
				return query.list();
			}
		}
		// 3.返回null
		return null;
	}

	public List<T> find(String hql, Object[] param)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.length > 0)
				{
					for (int i = 0; i < param.length; i++)
					{
						query.setParameter(i, param[i]);
					}
				}
				return query.list();
			}
		}
		return null;
	}

	public List<T> find(String hql, List<Object> param)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.size() > 0)
				{
					for (int i = 0; i < param.size(); i++)
					{
						query.setParameter(i, param.get(i));
					}
				}
				return query.list();
			}
		}
		return null;
	}

	public List<T> find(String hql, Object[] param, Integer page, Integer rows)
	{
		if (page == null || page < 1)
		{
			page = 1;
		}
		if (rows == null || rows < 1)
		{
			rows = 10;
		}
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.length > 0)
				{
					for (int i = 0; i < param.length; i++)
					{
						query.setParameter(i, param[i]);
					}
				}
				return query.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
			}
		}
		return null;
	}

	public List<T> find(String hql, List<Object> param, Integer page, Integer rows)
	{
		if (page == null || page < 1)
		{
			page = 1;
		}
		if (rows == null || rows < 1)
		{
			rows = 10;
		}
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.size() > 0)
				{
					for (int i = 0; i < param.size(); i++)
					{
						query.setParameter(i, param.get(i));
					}
				}
				return query.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
			}
		}
		return null;
	}

	public T get(Class<T> c, Serializable id)
	{
		if (this.getCurrentSession() != null && c != null && id != null)
		{
			return (T) this.getCurrentSession().get(c, id);
		}
		return null;
	}

	public T get(String hql, Object[] param)
	{
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0)
		{
			return l.get(0);
		}
		else
		{
			return null;
		}
	}

	public T get(String hql, List<Object> param)
	{
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0)
		{
			return l.get(0);
		}
		else
		{
			return null;
		}
	}

	public Long count(String hql)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				return (Long) query.uniqueResult();
			}
		}
		return null;
	}

	public Long count(String hql, Object[] param)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.length > 0)
				{
					for (int i = 0; i < param.length; i++)
					{
						query.setParameter(i, param[i]);
					}
					return (Long) query.uniqueResult();
				}
			}
		}
		return null;
	}

	public Long count(String hql, List<Object> param)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.size() > 0)
				{
					for (int i = 0; i < param.size(); i++)
					{
						query.setParameter(i, param.get(i));
					}
				}
				return (Long) query.uniqueResult();
			}
		}
		return null;
	}

	public Integer executeHql(String hql)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				return query.executeUpdate();
			}
		}
		return 0;
	}

	public Integer executeHql(String hql, Object[] param)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.length > 0)
				{
					for (int i = 0; i < param.length; i++)
					{
						query.setParameter(i, param[i]);
					}
				}
				return query.executeUpdate();
			}
		}
		return 0;
	}

	public Integer executeHql(String hql, List<Object> param)
	{
		if (hql != null && this.getCurrentSession() != null)
		{
			Query query = this.getCurrentSession().createQuery(hql);
			if (query != null)
			{
				if (param != null && param.size() > 0)
				{
					for (int i = 0; i < param.size(); i++)
					{
						query.setParameter(i, param.get(i));
					}
				}
				return query.executeUpdate();
			}
		}
		return 0;
	}
}
时间: 2024-10-26 04:50:40

hibernate BaseDao的相关文章

org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is

org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibern

错误:No Dialect mapping for JDBC type: -9

org.springframework.orm.hibernate3.HibernateSystemException: No Dialect mapping for JDBC type: -9; nested exception is org.hibernate.MappingException: No Dialect mapping for JDBC type: -9    at org.springframework.orm.hibernate3.SessionFactoryUtils.c

基于hibernate的BaseDao及其实现类的设计

以前做设计的时候dao接口和它的实现了,这样子就不必写这么多的重复代码了.但由于对反射没有了解,除非依赖hibernate的其他组件,否则写不出来.不过,有了反射,我们可以通过泛型来实现我们想要做的功能了. 首先是接口: package com.sms.dao.base; import java.util.List; public interface BaseDao<T> { public void add(T entity) throws Exception; public void del

hibernate HQL

package com.h3c.zgc.user.po; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="student") public class Student { @Id @Column(name="id") pr

spring,hibernate,spring框架整合

SSH框架作为javaEE最经典的框架, 初学者整合这几个框架可能也是一件比较头痛的事情(包括我自己), 下面来进行框架的整合!   一:   准备   SSH框架介绍 Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet, 处于MVC的控制层,Struts 2是Struts的下一代产品,个人认为: struts2~~struts+xwork; Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表

JavaEE笔记——BaseDao的使用

在Hibernate框架中使用BaseDao主要的作用是减少冗余代码,在对Dao的操作中CRUD可以说是最普通最常见的操作了,基本上面对不同的数据表都会有类似的CRUD操作,BaseDao的思想就是把这些冗余的操作抽取出来,所以不需要在spring框架的applicationContext.xml中注册,这可能是与其他Dao不同之处.作为一个抽象出来的类,使用这个BaseDao可以使我们的代码更优雅 第一步:和普通Dao一样,先创建个接口 接口中实现的方法有add(添加),update(更新),

spring+hibernate注解配置实例

简单的spring3.2.9和hibernate3的集成配置,有demo供下载.shTest下载 第一步 jdbc.properties配置 driverClassName=com.mysql.jdbc.Driver url=jdbc\:mysql\://localhost\:3306/shtest username=root password=123456 prototypeCount=1 maxActive=100 houseKeepingSleepTime=60000 minimumCon

hibernate的多层优化问题

刚开始接触数据库的时候,连mvc是什么都不到.直到开始学hibernate的时候才开始有了分层的思想.但是,即使有了这最基本的概念,写出来的代码冗余度还是比较高的. 比如说,如果我想要添加一条用户记录,则代码如下 用户类: package entity; public class User { private int user_id; private String username; private String password; public int getUser_id() { retur

spring 4 + jpa(hibernate 3/4) + spring mvc 多数据源配置

先从persistence.xml开始: <?xml version=”1.0″ encoding=”UTF-8″?><persistence version=”2.1″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence