Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在JPA查询中连接日期和时间以形成DATETIME(时间戳)?_Java_Hibernate_Datetime_Jpa - Fatal编程技术网

Java 如何在JPA查询中连接日期和时间以形成DATETIME(时间戳)?

Java 如何在JPA查询中连接日期和时间以形成DATETIME(时间戳)?,java,hibernate,datetime,jpa,Java,Hibernate,Datetime,Jpa,我在数据库中有两个字段来存储日期和时间。前者的时间部分设置为零,后者的日期部分设置为空(即1970/1/1)。上帝只知道最初的开发人员为什么这样做,我无法更改表。在JPA查询中,我需要将时间戳与这两个字段进行比较,就像它们是一个DateTime字段一样。在SQL Server中,我将执行以下操作: select CONVERT(DATETIME, CONVERT(CHAR(10), Date_Field, 121) + ' ' + CONVERT(CHAR(8), Time_Field, 108

我在数据库中有两个字段来存储日期和时间。前者的时间部分设置为零,后者的日期部分设置为空(即1970/1/1)。上帝只知道最初的开发人员为什么这样做,我无法更改表。在JPA查询中,我需要将时间戳与这两个字段进行比较,就像它们是一个DateTime字段一样。在SQL Server中,我将执行以下操作:

select CONVERT(DATETIME, CONVERT(CHAR(10), Date_Field, 121) + ' ' + CONVERT(CHAR(8), Time_Field, 108)) from MyTable

有没有办法在JPA查询中连接这两个字段,以便我可以将它们与完整的DateTime进行比较?

为什么不保持这种方式,我的意思是,如果不能更改结构,那么使用参数拆分,如果使用带参数的JPA查询,您可以明确: 进行查询

entityManager.createQuery("SELECT o FROM Object o WHERE o.date = :date AND o.time = :time", Object.class)
.setParameter("date", localDateTime.toDate())
.setParameter("time", localDateTime.toTime())
.getResultList();
@Transient //Only necesary if you are declaring the annotations at method level, not if they are in the variable
public DateTime getDateTime() {
    return new DateTime();//Build with the values dateTime and time
}
然后,在你的实体中,你只需要一个额外的方法,它将生成你想要的值 当您拥有结果列表时,您可以使用此bean属性访问值

entityManager.createQuery("SELECT o FROM Object o WHERE o.date = :date AND o.time = :time", Object.class)
.setParameter("date", localDateTime.toDate())
.setParameter("time", localDateTime.toTime())
.getResultList();
@Transient //Only necesary if you are declaring the annotations at method level, not if they are in the variable
public DateTime getDateTime() {
    return new DateTime();//Build with the values dateTime and time
}
关于你的约会问题,另一种方式(我知道,这很糟糕,但很有效)可能是:

SELECT r FROM Registry r Where
(r.date = :startDate AND r.time >= :startTime)
OR (r.date = :finalDate AND r.time <= :finalTime)
OR (r.date > :startDate AND r.date < :endDate)
从注册表r中选择r,其中
(r.date=:startDate和r.time>=:startTime)
或(r.date=:finalDate和r.time:startDate和r.date<:endDate)

这个查询的好处是它仍然在数据库中被过滤,避免了在JPA中传输和转换数据

我可以理解你的意思,但问题是如何使用date-between-DateTimes选择一系列记录。如果我使用一个where子句表示日期,使用另一个where子句表示时间,我将获得一组不同的记录(我将获得日期X和Y之间每天时间a和B之间的所有记录,而不是X+a和Y+B之间的所有记录)。我以与您的建议类似的方式“解决”了这个问题:我只按日期获取记录,然后对结果列表应用时间过滤器(jpa qyery之外)。所以+1。@RafaelDiasdaSilva我已经更新了我的答案,以解决日期之间的问题