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
We have different types of Date:
- DATE to save a date without time information,
- TIME to store a time without a date, and
- 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.
2 Comments
harsh 1868
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.
Renis1235
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.