= :timeFrom AND bs.timeFrom t-6ren">
gpt4 book ai didi

java - Spring Boot Data JPA 查询不适用于 LocalDateTime.MAX

转载 作者:行者123 更新时间:2023-12-02 00:59:30 25 4
gpt4 key购买 nike

我有方法:

@Query(value = "SELECT bs FROM BookedSlot bs WHERE bs.timeFrom >= :timeFrom AND bs.timeFrom < :timeTo")
Set<BookedSlot> test(@Param("timeFrom") LocalDateTime fromTime, @Param("timeTo") LocalDateTime timeTo);

还有两个测试

    @Sql(scripts = "/test-data.sql")
@Test
public void test1() {
final Set<BookedSlot> res = unit.test(LocalDateTime.now(), LocalDateTime.MAX);
assertNotNull(res);
assertEquals(1, res.size());//fails
}

@Sql(scripts = "/test-data.sql")
@Test
public void test2() {
final Set<BookedSlot> res = unit.test(LocalDateTime.now(), LocalDateTime.of(2050,1,1,1,1));
assertNotNull(res);
assertEquals(1, res.size());//ok
}

test-data.sql

INSERT INTO booked_slots (id, created_at, updated_at, time_from, time_to, user_id, service_box_id)
VALUES (1, NOW(), NOW(), '2040-01-01 08:30:00.0', '2040-01-01 10:00:00.0', 1, 1);

测试1 - 失败

测试2 - 确定

BookedSlots.java

@Entity
@Table(name = "booked_slots")
public class BookedSlot extends DbEntity implements Comparable<BookedSlot> {

@Column(name = "time_from")
private LocalDateTime timeFrom;
@Column(name = "time_to")
private LocalDateTime timeTo;
}

数据库h2(MySQL 5.7上也是如此,我只是使用H2进行集成测试)

test.properties

spring.datasource.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

对此有什么想法吗?

最佳答案

支持的最大LocalDateTime999999999-12-31T23:59:59.999999999。数据库不支持那么远的 future 日期。

MySQL range对于 DATETIME 值为 1000-01-01 00:00:00.0000009999-12-31 23:59:59.999999

<小时/>

hibernate-core: LiteralType::objectToSQLString Convert the value into a string representation, suitable for embedding in an SQL statement as a literal.

在这里你可以看到LocalDateTimeType::objectToSQLString方法

public class LocalDateTimeType
extends AbstractSingleColumnStandardBasicType<LocalDateTime>
implements VersionType<LocalDateTime>, LiteralType<LocalDateTime> {

public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss.S", Locale.ENGLISH );

//...

@Override
public String objectToSQLString(LocalDateTime value, Dialect dialect) throws Exception {
return "{ts '" + FORMATTER.format( value ) + "'}";
}

//..
}

对于LocalDateTime.MAX,它返回{ts '+999999999-12-31 23:59:59.9'}

关于java - Spring Boot Data JPA 查询不适用于 LocalDateTime.MAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60884477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com