Issue
I have developed simple application with Spring 4.2.5 + Hibernate 5.1.0 - database system is MS SQL Server 2014.
From few days I am struggling with correct storing time + timezone in database.
Requirements that I need to fulfill is:
To achieve it I created model called MyComment:
@Entity
@Table(name = "MY_COMMENT")
@EntityListeners(value = { MyCommentListener.class })
@Audited
public class MyComment implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "DATE_", nullable = false)
private Timestamp date;
...
}
To enforce saving dates in UTC time zone I used Jadira framework:
hibProperties.put("jadira.usertype.autoRegisterUserTypes", true);
hibProperties.put("jadira.usertype.javaZone", "UTC");
hibProperties.put("jadira.usertype.databaseZone", "UTC");
However during each create/update operation of MyComment object, MyCommentListener is getting date from my local timezone (not UTC date!):
public class MyCommentListener {
@PreUpdate
@PrePersist
public void setLastUpdate(MyComment myComment) {
myComment.setDate(new Timestamp(System.currentTimeMillis()));
}
}
Do you know how can I solve this issue?
- Should I use other date type in my model? Different than Timestamp?
- What kind of type should be DATE_ column in MS SQL server database?
I will appreciate any help. Thank you.
Solution
It was very strange for me that there's no property in Spring to set up default TimeZone - at least I do not know about it.
After some googling I found out that the best place in Spring to set time zone is WebApplicationInitializer
, so I prepared following code:
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
setupTimeZone();
}
private void setupTimeZone() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
}
Answered By - bontade
Answer Checked By - Senaida (JavaFixing Volunteer)