如何在休眠条件中转换日期类型
我有一个情况。我的mysql数据库中有两种日期。一个是日期,另一个是日期时间。现在,在休眠标准中,我必须检查一个日期是否大于另一个日期?
criteria.add(Restrictions.lt("award.deadline", "submission.date_received"));
但不同的类型会导致显示“java.lang.ClassCastException:java.lang.String 无法转换为 java.util.Date”的问题。
即使我尝试使用日期解析器来解析它,但它并没有将其视为日期,因为它仅将其视为字符串。那么,您能告诉我如何在休眠条件内将一个日期转换为不同类型吗?
I have a situation. I have two kinds of date in the mysql database. One is date and another is datetime. Now in hibernate criteria I have to check whether one date is greater than the other or not?
criteria.add(Restrictions.lt("award.deadline", "submission.date_received"));
But the different types are causing problems showing "java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date".
Even I tried to parse it using date parser but it is not taking as date as it is taking as string only. So, can you tell me how can we convert one date to different type inside the hibernate criteria?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,
Restrictions.lt(String propertyName, Object value)
是错误的限制。您需要的是Restrictions.ltProperty(String propertyName, String otherPropertyName)
。说明:
Restrictions.lt(String propertyName, Object value)
是将实体属性与特定 Value 进行比较Restrictions.ltProperty(String propertyName, String otherPropertyName)
是将实体属性与特定 Value 进行比较两个实体属性如果您使用 Restrictions.lt("Y", "X") 并且“Y”是日期属性的名称,那么 hibernate 会尝试将“X”转换为日期(不是列名),并且将“X”解析为日期有点复杂 - 因此会引发异常。
The problem is, that
Restrictions.lt(String propertyName, Object value)
is the wrong Restriction. What you need isRestrictions.ltProperty(String propertyName, String otherPropertyName)
.Explanation:
Restrictions.lt(String propertyName, Object value)
is to compare a entity property with a specific ValueRestrictions.ltProperty(String propertyName, String otherPropertyName)
is to compare a two entity propertiesIf you use
Restrictions.lt("Y", "X")
and "Y" is the name of a date property, then hibernate would try to translate "X" to an Date (not to an column name), and parsing "X" to an Date is, lets say, a bit complicated - so the Exception is rised.