简体   繁体   English

使用 Postgres 创建具有“日期”数据类型的属性时,Hibernate 和 JPA 中的问题

[英]Issue in Hibernate and JPA with Postgres while creating a attribute with “Date” datatype

I'm trying to create a table using hibernate and JPA with Postgres, and In one of the POJO, I have a timestamp attribute with Data type Date(java.util.date).我正在尝试使用 hibernate 和 JPA 和 Postgres 创建一个表,并且在其中一个 POJO 中,我有一个时间戳属性,数据类型为 Date(java.util.date)。 and when I see it in Postgres it's converted to data type "date without timezone" while I want date with timezone, What should I do now?当我在 Postgres 中看到它时,它被转换为数据类型“没有时区的日期”,而我想要带时区的日期,我现在该怎么办?

We have different types of Date :我们有不同类型的Date

  1. DATE to save a date without time information, DATE保存没有时间信息的日期,
  2. TIME to store a time without a date, and TIME存储没有日期的时间,以及
  3. TIMESTAMP to store date and time information. TIMESTAMP用于存储日期和时间信息。

And to map our variable to the specific type, we have to use @Temporal tag:而对于map我们的变量到具体的类型,我们必须使用@Temporal标签:

Small Example:小例子:

@Entity
public class MyEntity {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
     
    @Temporal(TemporalType.TIMESTAMP)
    private Date utilDate;
     
    @Temporal(TemporalType.DATE)
    private Calendar utilCalendar;

    // Getters, Setters ...
}

So I would suggest you save it as a TIMESTAMP所以我建议你将它保存为TIMESTAMP

To specify the Time Zone in your Propeties file, use:要在属性文件中指定时区,请使用:

spring.jpa.properties.hibernate.jdbc.time_zone = UTC

If you DON'T want to use @Timestamp , just declare your variable/column this way:如果您不想使用@Timestamp ,只需以这种方式声明您的变量/列:

@Column
private LocalDateTime created;

And it will be automatically mapped by Hibernate into a Timestamp for your Postgresql.它将由 Hibernate 自动映射到您的 Postgresql 的时间戳中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM