如何在休眠中比较日期 [英] How to compare dates in hibernate

查看:87
本文介绍了如何在休眠中比较日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中日期为 2012-04-09 04:02:53 2012-04-09 04:04:51 2012-04-08 04:04:51 等,我需要检索那里有当前日期在那里日期字段的数据。我的意思是我只需要匹配 2012-04-09'。我如何使用hibernate标准来做到这一点。

解决方案

使用 Restrictions.between()生成where子句,其中日期列在'2012-04-09 00:00:00'和'2012-04-09 23:59:59'之间

  SimpleDateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); 
Date fromDate = df.parse(2012-04-09 00:00:00);
日期toDate = df.parse(2012-04-09 23:59:59);

criteria.add(Restrictions.between(dateField,fromDate,toDate));

请注意,Criteria API中使用的所有属性都是Java属性名称,但不是实际的列名称。






更新:仅使用JDK从当前日期获取fromDate和toDate

 日历日历= Calendar.getInstance(); 
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
Date fromDate = calendar.getTime();

calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);
日期toDate = calendar.getTime();

criteria.add(Restrictions.between(dateField,fromDate,toDate));


In my Data base dates are as 2012-04-09 04:02:53 2012-04-09 04:04:51 2012-04-08 04:04:51, etc, I need to retrieve data which have current date in there date field. I mean i need to match only 2012-04-09' . How can i do it using hibernate criteria.

解决方案

Use Restrictions.between() to generate a where clause which the date column is between '2012-04-09 00:00:00' and '2012-04-09 23:59:59'

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse("2012-04-09 00:00:00");
Date toDate = df.parse("2012-04-09 23:59:59");

criteria.add(Restrictions.between("dateField", fromDate, toDate));

Please note that all the properties used in the Criteria API is the Java property name , but not the actual column name.


Update: Get fromDate and toDate for the current date using JDK only

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date fromDate = calendar.getTime();

calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date toDate = calendar.getTime();

criteria.add(Restrictions.between("dateField", fromDate, toDate));

这篇关于如何在休眠中比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆