1

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 ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

TemporalType is a better solution. One another might be to provide columnDefinition with column annotation on attribute and it will take whatever datatype you provide in columnDefinition.
Yes, you are correct. But the best solution would be to use LocalDateTime since it is part of the new Time api. Still, your comment adds yet another solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.