hibernate BaseDao

本文详细探讨了Hibernate中的BaseDao,解释了其在持久化层中的作用,如何简化数据库操作,以及BaseDao的设计原理和实现方式。通过实例,阐述了BaseDao如何整合ORM映射,提高开发效率,并讨论了它在实际项目中的应用和优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.doshr.xmen.server.dao;

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
	 * @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 startResult
	 *            从第几条记录开始查询
	 * @param size
	 *            查询记录数
	 * @return the result list or null
	 */
	public List<T> findByPage(String hql, Object[] param, Integer startResult, Integer size);

	/**
	 * 查询集合(带分页)
	 * 
	 * @param hql
	 * @param startResult
	 * @param size
	 * @return
	 */
	public List<T> findByPage(String hql, Integer startResult, Integer size);

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

	/**
	 * 获得一个对象
	 * @param id
	 * @return Object or null
	 */
	public T load(Serializable id);

	/**
	 * 获得一个对象
	 * 
	 * @param hql
	 * @param param
	 * @return Object or null
	 */
	public T get(String hql, 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);

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

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

}


package com.doshr.xmen.server.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

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

@SuppressWarnings("all")
public class BaseDAOImpl<T> implements BaseDAO<T>
{
	private Class<T> clazz;

	/**
	 * 1、this代表该类的子类
	 * 2、this.getClass().getGenericSuperclass()代表该类
	 * 3、type.getActualTypeArguments()[0]就是T
	 * 4、type.getRawType()就是BaseDaoImpl
	 */
	public BaseDAOImpl()
	{
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class<T>) type.getActualTypeArguments()[0];
	}

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

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

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

	public Serializable save(T o)
	{
		Session session = this.getCurrentSession();
		Integer result = null;
		if (o != null && session != null)
		{
			result = (Integer) session.save(o);
		}
		if (result == null)
		{
			session.getTransaction().rollback();
		}
		return result;
	}

	public boolean delete(T o)
	{
		boolean result = false;
		Session session = this.getCurrentSession();
		if (o != null && session != null)
		{
			try
			{
				session.delete(o);
				result = true;
			}
			catch (Exception e)
			{
				session.getTransaction().rollback();
				result = false;
			}
		}
		return result;
	}

	public boolean update(T o)
	{
		boolean result = false;
		Session session = this.getCurrentSession();
		if (o != null && session != null)
		{
			try
			{
				session.update(o);
				result = true;
			}
			catch (Exception e)
			{
				session.getTransaction().rollback();
				result = false;
			}
		}
		return result;
	}

	public boolean saveOrUpdate(T o)
	{
		boolean result = false;
		Session session = this.getCurrentSession();
		if (o != null && session != null)
		{
			try
			{
				session.saveOrUpdate(o);
				result = true;
			}
			catch (Exception e)
			{
				session.getTransaction().rollback();
				result = false;
			}
		}
		return result;
	}

	public List<T> find(String hql)
	{
		Session session = getCurrentSession();
		if (hql != null && session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				return query.list();
			}
		}
		return null;
	}

	public List<T> find(String hql, Object[] param)
	{
		if (hql == null || !checkParam(param))
		{
			return null;
		}

		Session session = this.getCurrentSession();

		if (session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				for (int i = 0; i < param.length; i++)
				{
					query.setParameter(String.valueOf(i), param[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 (rows > 100)
		{
			rows = 100;
		}

		if (hql == null || !checkParam(param))
		{
			return null;
		}

		Session session = this.getCurrentSession();

		if (session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				for (int i = 0; i < param.length; i++)
				{
					query.setParameter(String.valueOf(0), param[i]);
				}
				return query.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
			}
		}
		return null;
	}

	@Override
	public List<T> findByPage(String hql, Object[] param, Integer startResult, Integer size)
	{
		if (startResult == null || startResult < 0)
		{
			startResult = 0;
		}
		if (size == null || size < 1)
		{
			size = 10;
		}
		if (size > 100)
		{
			size = 100;
		}

		if (hql == null || !checkParam(param))
		{
			return null;
		}

		Session session = this.getCurrentSession();

		if (session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				for (int i = 0; i < param.length; i++)
				{
					query.setParameter(String.valueOf(i), param[i]);
				}
				return query.setFirstResult(startResult).setMaxResults(size).list();
			}
		}
		return null;
	}

	@Override
	public List<T> findByPage(String hql, Integer startResult, Integer size)
	{
		if (startResult == null || startResult < 0)
		{
			startResult = 0;
		}
		if (size == null || size < 1)
		{
			size = 10;
		}
		if (size > 100)
		{
			size = 100;
		}

		if (hql == null)
		{
			return null;
		}

		Session session = this.getCurrentSession();

		if (session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				return query.setFirstResult(startResult).setMaxResults(size).list();
			}
		}
		return null;
	}

	public T get(Serializable id)
	{
		Session session = this.getCurrentSession();
		if (id != null && session != null)
		{
			return (T) session.get(clazz, id);
		}
		return null;
	}

	public T load(Serializable id)
	{
		Session session = this.getCurrentSession();
		if (id != null && id != null && session != null)
		{
			return (T) session.load(clazz, 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 Long count(String hql)
	{
		Session session = this.getCurrentSession();
		if (hql != null && session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				Object object = query.uniqueResult();
				if (object != null)
				{
					return (Long) object;
				}
			}
		}
		return null;
	}

	public Long count(String hql, Object[] param)
	{
		if (hql == null || !checkParam(param))
		{
			return null;
		}

		Session session = this.getCurrentSession();

		if (session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				for (int i = 0; i < param.length; i++)
				{
					query.setParameter(String.valueOf(i), param[i]);
				}
				return (Long) query.uniqueResult();
			}
		}
		return null;
	}

	public int executeHql(String hql)
	{
		Session session = this.getCurrentSession();
		int result = 0;
		if (hql != null && session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				try
				{
					result = query.executeUpdate();
				}
				catch (Exception e)
				{
					session.getTransaction().rollback();
				}
			}
		}
		return result;
	}

	public int executeHql(String hql, Object[] param)
	{
		int result = 0;
		if (hql == null || !checkParam(param))
		{
			return result;
		}
		Session session = this.getCurrentSession();
		if (session != null)
		{
			Query query = session.createQuery(hql);
			if (query != null)
			{
				for (int i = 0; i < param.length; i++)
				{
					query.setParameter(String.valueOf(i), param[i]);
				}
				try
				{
					result = query.executeUpdate();
				}
				catch (Exception e)
				{
					session.getTransaction().rollback();
				}
			}
		}
		return result;
	}

	private boolean checkParam(Object[] param)
	{
		if (param != null && param.length > 0)
		{
			for (int i = 0; i < param.length; i++)
			{
				if (param[i] == null)
				{
					return false;
				}
			}
			return true;
		}
		else
		{
			return false;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值