harsh 1868
harsh 1868

Reputation: 76

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). 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 ?

Upvotes: 1

Views: 1348

Answers (1)

Renis1235
Renis1235

Reputation: 4700

We have different types of Date:

  1. DATE to save a date without time information,
  2. TIME to store a time without a date, and
  3. TIMESTAMP to store date and time information.

And to map our variable to the specific type, we have to use @Temporal tag:

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

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:

@Column
private LocalDateTime created;

And it will be automatically mapped by Hibernate into a Timestamp for your Postgresql.

Upvotes: 2

Related Questions