`

HQL 处理日期比较 SQL Server

阅读更多

       Hibernate很大的一个特点就是屏蔽了数据库的差异,使用了hibernate就应该尽量HQL来操作数据库(除非不得不用数据库本身的一些特性),对于日期、时间类型的比较hibernate也提供很好的支持。

 

这里提供两种方式来处理HQL 日期、时间比较问题!

 

   一、常用

        

HQL:   * and acceptDate<=:end

    用一个时间类型来替换参数end:query.setDate("end",endDate);

    例:

java.sql.Date   beginDate=java.sql.Date.valueOf("2006-6-1");   
java.sql.Date   endDate=java.sql.Date.valueOf("2006-6-2");   
    
Stirng hql = "from table tb where tb.startdate <:endDate and tb.startdate >=:beginDate";  

Query query = session.createQuery(hql);
    
query.setDate("beginDate",beginDate);   
query.setDate("endDate",endDate);

 二、优化

  

String hql = "from TradeRecord as tr where tr.TradeTime>= :startTime " 
                   + "and tr.TradeTime <= :endTime and tr.CustomerId =:cid"; 

String[] params = { "startTime", "endTime", "cid" }; 

Object[] args = { startTime, endTime, new Long(cid) }; 

List liste = this.getHibernateTemplate().findByNamedParam(hql, params, args);

//startTime,endTime,cid是这个方法的参数

特别提醒:

 

     当遇到查询从A(起始时期)到B(结束日期)的纪录时,

     如果数据库中字段类型为timestamp,那么查询2008-10-10到2008-11-11的纪录时不会出现2008-10-10那一天的纪录,哪怕你的比较符号用的是>=和<=;因为数据库中的2008-10-10的纪录是这样的格式

   2008-11-11 15:35:48:253,而query.setDate设置一个时间参数进去,他是用这个时间比较的
   2008-11-44 00:00:00 000,所以因该用:
query.setTimeStamp("end",endDate);
 如果从view层取到的date不包含后面的time信息,最好                   
                   endDate.setHours(23);
                   endDate.setMinutes(59);
                   endDate.setSeconds(59);
  对开始时间                  
                   startDate.setHours(0)
                   startDate.setMinutes(0);
                   startDate.setSeconds(0);
 
这样就是查询 A-0:0:0 到 B-23:59:59时间段的数据 
分享到:
评论
3 楼 nanjiwubing123 2012-04-28  
不错  不错 
2 楼 accphc 2009-05-19  
Stirng hql = "from table tb where tb.startdate <2009-6-1 and tb.startdate >=2008-6-1";
1 楼 accphc 2009-05-19  
Stirng hql = "from table tb where tb.startdate <2008-6-1 and tb.startdate >=2009-6-1";

相关推荐

Global site tag (gtag.js) - Google Analytics