对HibernateTemplate的扩展:封装上自己需要的逻辑形成新方法(不断更新)

用HibernateTemplate时,发现确实在编写代码上省了不少的事,但是在实际用时,它又没有Query对象那样给出那么多方法,所以有时需要我们自己封装一些:

今天工程刚开头,我封装了两个,估计以后会封装更多。  主要是用回调方法来进行封装。


1.分页:

/**升级getHibernateTemplate:分页操作
 * @param hql    HSQL 查询语句
 * @param offset 开始取数据的下标
 * @param length 读取数据记录数
 * @return List    结果集
 */
protected List<Vehicle> fetchByPageBean(final int startIndex, final int pageSize,final String hql) throws Exception {
 List list = null;
 try {
  list = this.getHibernateTemplate().executeFind(
    new HibernateCallback() {
    public Object doInHibernate(Session session) throws HibernateException, SQLException {
    Query query = session.createQuery(hql);
    query.setFirstResult(startIndex);
    query.setMaxResults(pageSize);
    List<Vehicle> list = query.list();
    return list;
    }
    });
 } catch (Exception e) {
  throw e;
 }
 return list;
}


2.根据id删除记录

 protected void deleteByVehicleId(final int vehicleId) throws Exception {
 try {
 this.getHibernateTemplate().executeFind(
 new HibernateCallback() {
 public Object doInHibernate(Session session) throws HibernateException, SQLException {
 Query q = session.createQuery("delete from Vehicle v where v.id=" + vehicleId );
 q.executeUpdate();
 return null;
 }
 });
 } catch (Exception e) {
 throw e;
 }
}


posted on 2012-05-07 18:50  java课程设计例子  阅读(173)  评论(0编辑  收藏  举报