hibernate使用sum聚集函数,时间段为查询条件连接SQL2005

public Integer getLaneFee(Integer no, Date fromTime, Date toTime) { SimpleDateFormat sqlDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Session session = null; StringBuffer hql = new StringBuffer( "select sum(mount) from Table as p where p.no=" + no); hql.append(" and p.tolltime >= '" + sqlDateFormat.format(fromTime) + "' and p.tolltime <= '" + sqlDateFormat.format(toTime) + "'"); int count = 0; try { session = this.getSessionFactory().openSession(); // 有可能连接耗尽了,无法打开session Query query = session.createQuery(hql.toString()); count = ((Number) query.uniqueResult()).intValue(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != session) { session.close(); // 不论是否发生异常了,都需要关闭,以免影响整个系统的运行 } } return count; }

 

1 Date类型的时间用于比较SQL2005里的Timestamp,需要转换格式:

SimpleDateFormat sqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

sqlDateFormat.format(new Date());

然后才能使用数据库的时间字段和查询条件比较

 

2 获取结果的语句,参考

http://fengzhiyin.javaeye.com/blog/376631

//参考代码 //第一种方法: Integer count = (Integer)getHibernateTemplate().find(hql).listIterator().next(); return count.intValue(); //第二种方法: return ((Integer)getHibernateTemplate().iterate(hql).next()).intValue(); //第三种方法: Query query = getHibernateTemplate().createQuery( getSession(),hql); return ((Integer)query.uniqueResult()).intValue(); /** * @TODO:查询某一年度的所有计划数量 */ public int findCountByYear(String currYear) { String hqlString = "select count(*) from WaterPlan as p where p.planYear ='"+currYear+"'"; Query query = this.getSession().createQuery(hqlString); return ((Number)query.uniqueResult()).uniqueResult(); }

你可能感兴趣的:(sql,Hibernate,Date,session,Integer,query)