【问题标题】:What's the best way to store date in spring boot jpa?在 Spring Boot jpa 中存储日期的最佳方法是什么?
【发布时间】:2021-11-07 11:25:14
【问题描述】:

在 Spring Boot 实体中存储数据库日期的最佳方式是什么?

例如,在我的数据库中,我需要像 2021-02-19 17:00 这样存储 smth,然后在我的 spring boot 应用程序中构建查询

【问题讨论】:

  • 考虑使用LocalDateTime
  • 这真的取决于确切的查询。你没有提供任何关于你打算做什么的信息。
  • 是的;在您的服务方法中创建两个LocalDateTime,然后将它们绑定到存储库方法中的准备好的语句。
  • 鉴于这是为了定义一个时间点,请在您的数据库中使用 timestamp with time zone(或等效项),在 Java 中使用 OffsetDateTime。你应该使用OffsetDateTIme 有点好笑,但它与timestamp with time zone 配合得很好,而且你总是可以在Java 中与其他类型相互转换。只是不要使用其他人建议的LocalDateTimeclass,因为它没有定义时间点。

标签: java spring spring-boot hibernate spring-data-jpa


【解决方案1】:

在数据库中使用 LocalDateTime 和适当的日期列类型。然后,如果需要,您将能够在数据库查询和 Java 中轻松地进行日期数学运算(例如比较)。

【讨论】:

  • 顺便说一句,我通常也不会使用 LocalDateTime,但问题是关于存储没有时区信息的日期和时间,我仍然认为 LocalDateTime 适合于此。在大多数情况下,您需要一个时区,因此需要一个 ZonedDateTime,但这不是所要求的。
  • @GreyBeardedGeek 那么,我可以在像@Column(name="time") private ZonedDateTime time; 这样的实体类中使用 ZonedDateTime 吗?或者它需要一些 JSON 序列化程序选项来重写 BTW 我使用 postgresql
  • 是的,但有一些注意事项。例如,请参阅thorben-janssen.com/map-date-time-api-jpa-2-2
【解决方案2】:

如果您想将日期作为字符串存储在数据库中,您有很多选择,但我认为回答哪个更好,这完全取决于您的数据库和映射策略,例如考虑

DateTimeFormatter firstFormatter = DateTimeFormatter.ofPattern("dd, MMM, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.of(2021, Month.NOVEMBER, 7);
String firstDateAsString = firstFormatter.format(date);
System.out.println(firstDateAsString);

作为另一个例子,第一个firstFormatter.formate()接受TemporalAccessor

DateFormat secondFormatter = new SimpleDateFormat("dd MM yyyy");
String secondDateAsString= secondFormatter.format(new Date());
System.out.println(secondDateAsString);

请注意,休眠查询负载和执行时间将完全取决于您的映射和标记化按日期累积的字符串。

【讨论】:

  • (1) 问题说在我的数据库中我需要像2021-02-19 17:00 那样存储smth。如果此答案确实满足某人的需求,则您无法将其放入您的 sn-ps (2) 中,那么第一个 sn-p 就是要使用的。强烈建议不要使用DateFormatSimpleDateFormatDate。这些课程出了名的麻烦和过时。
猜你喜欢
  • 2016-12-22
  • 2013-06-14
  • 2017-09-18
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
相关资源
最近更新 更多