使用SQL比较日期Java到DateTime数据库表中的列 [英] Compare Date Java to DateTime Column in database table using SQL

查看:119
本文介绍了使用SQL比较日期Java到DateTime数据库表中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Date 将在sql查询中分配给某些变量的Java对象(因为我使用Hibernate),以便将它们与 DateTime 键入列以获取指定时间范围的行,例如:

  WHERE event_date> =:startDate和event_date< :finishDate 

我无法直接比较日期到datetime,所以我想到了两个可能的解决方案: p>


  • 在比较之前,尝试使用查询到date字段来转换event_date字段。

  • 或尝试转换日期java对象到dateTime我认为可能不可能..



你会建议我做什么?

解决方案

我想你有问题,因为你使用 setDate (如果我是错误)和 setDate 方法:


绑定日期(时间是给定的 Date 对象指向一个命名查询参数


使用 setTimestamp ,它绑定给定 Date 日期和时间对象:

  java.util.Date startDate = ...; 
java.util.Date finishDate = ...;
Query query = session.createQuery(from YourTable where event_date> =:startDate and event_date<:finishDate);
query.setTimestamp(startDate,startDate);
query.setTimestamp(finishDate,finishDate);

 

ps:一定要使用 java.util.Date 对象和 java.sql.Date 一个。


I've got two Date Java objects which will be assigned to some variables in sql query (because I use Hibernate) in order to compare them with a DateTime type column to get rows with a specified time range, for example:

  WHERE event_date >= :startDate and event_date < :finishDate

I couldn't compare date to datetime directly so I thought of 2 possible solutions:

  • Try to convert event_date field using a query to date field before the comparison.
  • Or try to convert date java object to dateTime which I think might not be possible..

What would you suggest me to do?

解决方案

I guess you have the problems because you use setDate (correct me if I'm wrong) and setDate method:

Binds the date (time is truncated) of a given Date object to a named query parameter.

Use setTimestamp instead, which binds the date and time of a given Date object:

java.util.Date startDate = … ;
java.util.Date finishDate = … ;
Query query = session.createQuery("from YourTable where event_date >= :startDate and event_date < :finishDate");
query.setTimestamp("startDate", startDate);
query.setTimestamp("finishDate", finishDate);

 
p.s.: be sure to use java.util.Date object and NOT the java.sql.Date one.

这篇关于使用SQL比较日期Java到DateTime数据库表中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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