JPA 查询使用 Between 和 Instant 不起作用

Chr*_*one 5 mysql jpql mariadb spring-data-jpa spring-boot

我正在尝试进行查询以检索在两个日期之间创建的一些数据(表示为即时)。

下面是我正在使用的实体的摘录:

@Entity
public class HistoricalData {
@Id
@GeneratedValue
private Long id;

@Column
private String name;

@CreationTimestamp
private Instant timestamp;

@Column
private Double price;

}
Run Code Online (Sandbox Code Playgroud)

我编写的查询是为了检索两个 Instant 之间的数据;

@Query("select h from HistoricalData h where h.timestamp between :timestampStart and :timestampEnd and upper(name) = upper(:name)")
List<HistoricalData> findHistoricalDataBetween(@NonNull Instant timestampStart, @NonNull Instant timestampEnd, @NonNull String name);
Run Code Online (Sandbox Code Playgroud)

它产生这个 SQL 查询:

select historical0_.id as id1_5_, historical0_.price as price2_5_, historical0_.timestamp as timestam3_5_ from historical_data historical0_ where (historical0_.timestamp between ? and ?) and upper(historical0_.name)=upper(?)
Run Code Online (Sandbox Code Playgroud)

我还编写了“hibernate JPA”查询只是为了尝试但没有成功:

List<HistoricalData> findHistoricalDataByTimestampAfterAndTimestampBeforeAndName(@NonNull Instant timestampStart, @NonNull Instant timestampEnd, @NonNull String name);
Run Code Online (Sandbox Code Playgroud)

请记住,上述所有查询都可以正确编译并且不会引发任何异常,它们只是从数据库中检索不到任何内容

我使用的数据库是最新版本的 MariaDB,连接器版本是 2.7.2 我使用的 SpringBoot 版本是 2.5.3

以下是表定义中的 DDL(从 Hibernate 自动生成):

create table historical_data
(
id        bigint   not null primary key,
price     double   null,
timestamp datetime not null,
name      varchar  not null
);
Run Code Online (Sandbox Code Playgroud)

这是时间戳在数据库中的样子:

在此输入图像描述

即使这两个即时之间的记录存在于数据库中,我仍然没有从查询中得到任何结果。

v.l*_*nev 0

看起来原因是时区。MySQL 驱动程序使用不正确的时区转换,使用默认本地时区代替连接时区(反之亦然)。

只需在 MySQL 驱动程序中调试此查询即可享受乐趣并弄清楚会发生什么。

您可以将参数添加到数据库 URL 以查看为准备语句传递了哪些实际值

jdbc:mysql://<DATABASE_URL>?logger=com.mysql.cj.log.Slf4JLogger&profileSQL=true
Run Code Online (Sandbox Code Playgroud)