`

Hibernate3 Template Dao

 
阅读更多
package com.king.stt.dao;

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

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.king.util.hibernate.Page;

public interface IDao { 
	/**
	 * <b>function:</b> 暴露HibernateTemplate模板,当基类(增删改查组件)方法不够用可以用模板进行操作
	 * 
	 * @return HibernateTemplate
	 */
	public HibernateTemplate getHibernateTemplate();

	public <T> Serializable save(T entity) throws Exception;

	public <T> boolean update(T entity) throws Exception;
	
	public <T> void saveOrUpdate(T entity) throws Exception;

	public <T> boolean delete(T entity) throws Exception;

	public <T> boolean deleteAll(Collection<T> entities) throws Exception;

	public <T> T get(Class<T> c, Serializable id) throws Exception;

	public <T> T get(String hql, Object... args) throws Exception;

	public int executeByHql(String hql, Object... args) throws Exception;

	public int executeBySql(String sql) throws Exception;

	public <T> List<T> findByHql(String hql, Object... args) throws Exception;

	public <T> List<T> findBySql(String sql) throws Exception;

	public <T> List<T> findAll(Class<T> c) throws Exception;

	/**
	 * <b>function:</b> 传入查询语句和查询总条数(总记录)的hql语句、当前页数、每页显示调试数;返回查询后的list集合; list集合保存总记录调试和记录结果
	 * 
	 * @param queryHql
	 *            查询记录hql语句
	 * @param queryCountHql
	 *            查询记录条数hql语句
	 * @param firstResult
	 *            当前查询页
	 * @param maxResult
	 *            每页显示多少条
	 * @return List返回集合 集合0保存查询结果、集合1保存总记录条数
	 * @throws Exception
	 */
	public <T> List<T> queryForPage(String queryHql, String queryCountHql, int firstResult, int maxResult, Object... args) throws Exception;

	/**
	 * <b>function:</b> 传入查询语句和查询总条数(总记录)的hql语句、page分页对象;返回查询后的list集合;
	 * 
	 * @createDate 2010-8-3 上午11:16:59
	 * @author hoojo
	 * @param queryHql
	 *            list集合结果查询
	 * @param queryCountHql
	 *            总记录调试查询
	 * @param page
	 *            分页对象
	 * @throws Exception
	 */
	public <T> void queryForPage(String queryHql, String queryCountHql, Page<T> page, Object... args) throws Exception;

	/**
	 * <b>function:</b> 分页查询,传入查询count的hql语句和DetachedCriteria动态查询条件进行查询分页
	 * 
	 * @param queryCountHql
	 *            hql查询count语句总条数
	 * @param cResult
	 *            DetachedCriteria 动态查询条件
	 * @param firstResult
	 *            起始
	 * @param maxResult
	 *            最大页数
	 * @return List<?> 查询集合
	 * @throws Exception
	 */
	public <T> List<T> queryForPage(String queryCountHql, DetachedCriteria cResult, int firstResult, int maxResult) throws Exception;

	/**
	 * <b>function:</b> 分页查询,传入查询的count的hql语句和动态查询DetachedCriteria类及page分页entity
	 * 
	 * @createDate 2010-8-3 上午11:14:30
	 * @author hoojo
	 * @param queryCountHql
	 *            查询count语句
	 * @param cResult
	 *            DetachedCriteria 动态查询条件类
	 * @param page
	 *            Page分页实体类
	 * @throws Exception
	 */
	public <T> void queryForPage(String queryCountHql, DetachedCriteria cResult, Page<T> page) throws Exception;

	/**
	 * <b>function:</b> 传入查询条件DetachedCriteria进行查询
	 * 
	 * @createDate 2010-8-3 上午11:55:28
	 * @author hoojo
	 * @param <T>
	 *            类型
	 * @param dc
	 *            DetachedCriteria动态条件查询
	 * @return List
	 * @throws Exception
	 */
	public <T> List<T> find(DetachedCriteria dc) throws Exception;

}

 

DaoImpl

package com.king.stt.dao;

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

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.king.util.hibernate.Page;

@Repository(value = "dao")
public class DaoImpl extends HibernateDaoSupport implements IDao {

	@Resource
	public void setSessionFacotry(SessionFactory sessionFacotry) {
		super.setSessionFactory(sessionFacotry);
	}

	@Override
	public <T> Serializable save(T entity) throws Exception {
		return this.getHibernateTemplate().save(entity);
	}
	
	@Override
	public <T> void saveOrUpdate(T entity) throws Exception {
		this.getHibernateTemplate().saveOrUpdate(entity);
	}

	@Override
	public int executeByHql(String hql, Object... args) throws Exception {
		return this.getHibernateTemplate().bulkUpdate(hql, args);
	}

	@Override
	public int executeBySql(String sql) throws Exception {
		return this.getSession().createSQLQuery(sql).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> findBySql(String sql) throws Exception {
		List<T> list = null;
		try {
			list = (List<T>) this.getSession().createSQLQuery(sql).list();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	@Override
	public <T> boolean update(T entity) throws Exception {
		boolean bo = false;
		try {
			this.getHibernateTemplate().update(entity);
			bo = true;
		} catch (Exception e) {
			bo = false;
			throw new RuntimeException(e);
		}
		return bo;
	}

	@Override
	public <T> boolean delete(T entity) throws Exception {
		boolean bo = false;
		try {
			this.getHibernateTemplate().delete(entity);
			bo = true;
		} catch (Exception e) {
			bo = false;
			throw new RuntimeException(e);
		}
		return bo;
	}

	@Override
	public <T> T get(Class<T> c, Serializable id) throws Exception {
		T ety = null;
		try {
			ety = (T) this.getHibernateTemplate().get(c, id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return ety;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T get(String hql, Object... args) throws Exception {
		T ety = null;
		try {
			Query query = this.getSession().createSQLQuery(hql);
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					query.setParameter(i, args[i]);
				}
			}
			ety = (T) query.setMaxResults(1).uniqueResult();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return ety;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> findByHql(String hql, Object... args) throws Exception {
		List<T> list = null;
		try {
			list = this.getHibernateTemplate().find(hql, args);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> findAll(Class<T> c) throws Exception {
		List<T> list = null;
		try {
			list = (List<T>) this.getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(c));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> queryForPage(String queryHql, String queryCountHql, int firstResult, int maxResult, Object... args) throws Exception {
		List<T> list = new ArrayList<T>();
		try {
			Session session = this.getSession();
			Query query = session.createQuery(queryHql);
			for (int i = 0; i < args.length; i++) {
				query.setParameter(i, args[i]);
			}
			list.add((T) query.setFirstResult(firstResult).setMaxResults(maxResult).list());
			Query count = session.createQuery(queryCountHql);
			for (int i = 0; i < args.length; i++) {
				count.setParameter(i, args[i]);
			}
			list.add((T) count.setMaxResults(1).uniqueResult());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> void queryForPage(String queryHql, String queryCountHql, Page<T> page, Object... args) throws Exception {
		try {
			Session session = this.getSession();
			Query query = session.createQuery(queryHql);
			for (int i = 0; i < args.length; i++) {
				query.setParameter(i, args[i]);
			}
			page.setResult(query.setFirstResult(page.getCurrentPage()).setMaxResults(page.getPageSize()).list());
			Query count = session.createQuery(queryCountHql);
			for (int i = 0; i < args.length; i++) {
				count.setParameter(i, args[i]);
			}
			page.setTotalsCount(Integer.parseInt(count.setMaxResults(1).uniqueResult().toString()));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> queryForPage(String queryCountHql, DetachedCriteria cResult, int firstResult, int maxResult) throws Exception {
		List<T> list = new ArrayList<T>();
		try {
			Session session = this.getSession();
			list.add((T) this.getHibernateTemplate().findByCriteria(cResult, firstResult, maxResult));
			list.add((T) session.createQuery(queryCountHql).setMaxResults(1).uniqueResult());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> find(DetachedCriteria dc) throws Exception {
		List<T> list = new ArrayList<T>();
		try {
			list = (List<T>) this.getHibernateTemplate().findByCriteria(dc);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> void queryForPage(String queryCountHql, DetachedCriteria cResult, Page<T> page) throws Exception {
		try {
			Session session = this.getSession();
			page.setResult(this.getHibernateTemplate().findByCriteria(cResult, page.getCurrentPage(), page.getPageSize()));
			page.setTotalsCount(Integer.parseInt(session.createQuery(queryCountHql).setMaxResults(1).uniqueResult().toString()));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public <T> boolean deleteAll(Collection<T> entities) throws Exception {
		boolean bo = false;
		try {
			this.getHibernateTemplate().deleteAll(entities);
			bo = true;
		} catch (Exception e) {
			bo = false;
			throw new RuntimeException();
		}
		return bo;
	}

}

 

分享到:
评论

相关推荐

    myeclipse中自动生成hibernate的POJO、DAO和hbm.xml文件

    3. 在Driver template选择需要的驱动模板,这里使用ORACLE数据库,并设定好数据库连接信息(url、username、password) 4. 在Driver JAR中,通过Add JARs添加数据库的驱动的jar包 5. 点击Test Driver,测试下该配置...

    springMVC+hibernate3整合

    3. **整合 Spring MVC 和 Hibernate** - 使用 Spring 的 `LocalSessionFactoryBean` 创建 SessionFactory 实例。 - 创建一个 DAO(数据访问对象)接口,实现数据操作的方法,如查询、添加、删除和更新。 - 使用 ...

    spring_hibernate整合实例

    3. **Hibernate Template或JPA**:Spring提供了HibernateTemplate,这是一个简化Hibernate操作的工具类。然而,随着Spring Data JPA的出现,现在更多地推荐使用JPA,它提供了一种基于标准的、与ORM供应商无关的方式...

    Spring-SpringMVC-Hibernate-Template:本项目为 Spring-SpringMVC-Hibernate 的空白模板

    3. **数据访问对象(DAO)**:DAO层负责与数据库交互,使用Hibernate的Session接口执行CRUD操作。 4. **服务层(Service)**:业务逻辑处理层,通常作为DAO和控制器之间的中间层,封装业务规则和流程。 5. **控制...

    myEclipse使用hibernate图解

    - 在“Driver template”中选择相应的数据库模板,比如 SQL Server 2008。 - “Driver name”用于自定义数据库驱动的名字,可以根据实际情况填写。 - “Connection URL”用于指定 JDBC 连接字符串,例如连接 SQL ...

    自定义 Hibernate Tools 的模板

    2. **模板语言**: Hibernate Tools 使用 Velocity 模板语言(Velocity Template Language, VTL)来定义模板。VTL 是一个轻量级的模板引擎,允许开发者用简单的语法来控制代码生成逻辑。 3. **自定义模板步骤**: -...

    hibernate学习心得

    对于 MySQL 数据库,你应该选择 "MySQL Connector/J" 作为 Driver Template,Driver Name 填写 "mysql",以便后续识别。配置 Connection URL 为 `jdbc:mysql://localhost:3306/数据库名`,其中 "数据库名" 需替换为...

    第25,26讲 --搭建和配置Spring与Hibernate整合的环境

    在Spring的配置文件中,我们可以使用Hibernate的Template或DAO来处理数据库操作。例如,创建一个HibernateTemplate Bean: ```xml &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate5....

    strut2与spring4与hibernate4整合

    5. **整合Spring和Hibernate**:在Spring配置文件中定义SessionFactory Bean,使用Hibernate的Template或SessionFactory来操作数据库。 6. **测试与调试**:编写JUnit测试用例,确保各个层次的交互正常工作,无异常...

    struts2与hibernate的整合实现数据的crud

    3. **配置Hibernate**:创建Hibernate的配置文件(hibernate.cfg.xml),设置数据库连接信息,以及实体类对应的映射文件(.hbm.xml)。还需要一个SessionFactory的配置,用于生成与数据库交互的对象。 4. **创建...

    spring,hibernate,struts

    2. `spring_integration_hibernate3_hibernateDaoSupport`:这部分可能涉及Spring对Hibernate 3的支持,尤其是HibernateDaoSupport类,它是Spring提供的基类,为DAO(Data Access Object)层提供了一些便利的方法,...

    Hibernate逆向工程-oracle示例借鉴.pdf

    在Driver template中选择Oracle驱动模板,输入正确的数据库连接信息,包括URL、username和password。在Driver JARs部分,你需要添加Oracle数据库的JDBC驱动jar包。测试驱动连接,如果出现因语言设置导致的问题,比如...

    Spring的DAO

    Spring的DAO设计模式主要体现在模板(Template)和回调(Callback)两个概念上。 模板类,如`JdbcTemplate`,负责处理数据访问流程中的通用部分,包括事务管理、资源的打开和关闭,以及异常的处理。这些模板类通常...

    ssh三大框架整合s2sh整合总结(struts2.1.8-spring2.5-hibernate3.2)

    5. **整合Spring与Hibernate**:配置Hibernate的SessionFactory Bean,使用Hibernate的Template或JPA API进行数据操作。 6. **编写Action、Service和DAO**:定义Action类处理请求,Service层封装业务逻辑,DAO层负责...

    hibernate配置

    - 完成后,MyEclipse将自动生成与`hibernateDemo`表对应的实体类和DAO类。 通过以上步骤,你已经在MyEclipse 6.5中成功配置了Hibernate,并为数据库中的表生成了相应的Java对象和数据访问对象。接下来,你可以开始...

    spring+hibernate集成

    4. **DAO(Data Access Object)抽象**:Spring提供Template类,如`HibernateTemplate`或`HibernateDaoSupport`,来简化Hibernate的使用。不过,更推荐使用Spring Data JPA或Spring Data JDBC,它们提供了更高级别的...

    Spring4+hibernate4+struts2整合框架

    这得益于Spring的AOP和Hibernate的Template模式。例如,Spring的HibernateTemplate或JpaTemplate可以提供通用的CRUD操作,而自定义的Dao只需定义特定的查询方法即可。这种设计模式提高了代码的复用性和可维护性。 ...

    java私塾独家首发最新Hibernate4教程

    学习如何在Spring中配置Hibernate,以及使用Spring的Template和DAO模式,可以提升代码的可维护性和测试性。 十、实战演练 理论知识与实践相结合才能更好地掌握Hibernate。本教程将引导你通过一系列实战项目,从简单...

Global site tag (gtag.js) - Google Analytics