【问题标题】:Data type of time in Spring-Data-RestSpring-Data-Rest中时间的数据类型
【发布时间】:2017-12-08 14:17:03
【问题描述】:

我想存储时间我应该在spring框架中使用什么数据类型? 我使用的数据库是 MySQL

@Entity
public class ShopDetail {

@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;
    }

【问题讨论】:

  • java.util.date 或 java.sql.date
  • @Temporal注解用于指定当前注解的java.util.Date或java.util.Calendar实体属性的TemporalType。

标签: java mysql spring spring-data-rest sqldatatypes


【解决方案1】:

如果您使用 Java 8,大多数业务逻辑实体字段可能使用 Instant - java.time API 中的基本类,用于以 UTC 时间线表示时刻。

如果需要时区数据,可以考虑使用:

ZonedDateTime 是具有时区的日期时间的不可变表示。这 类存储所有日期和时间字段

另一种选择LocalDateTime

在 ISO-8601 日历系统中没有时区的日期时间,例如 如 2007-12-03T10:15:30

但是,如果系统时区发生变化,您将依赖默认的系统时区,这可能会带来矛盾的结果。

查看Java 8: What's the difference between Instant and LocalDateTime?Hibernate with Java 8 LocalDate & LocalDateTime in Database 以获得明确的解释。

【讨论】:

    【解决方案2】:
    【解决方案3】:

    您可以在实体中使用 Java 8 时间类型。只需将此依赖项添加到您的项目中即可:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-java8</artifactId>
    </dependency>
    

    根据这篇文章The 5 laws of API dates and times,我建议在 REST 项目中使用ZonedDateTime

    还要注意这个topic...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-29
      • 2016-10-26
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多