问题
Using Hibernate/Envers, how to:
- Save UTC (instead of local) timestamps for Hibernate Envers revision info?
- Get timestamps as a LocalDateTime (Java 8)?
回答1:
1) From the revision listener, call the fixTimezone
method of the revision, as shown below.
2) To get it as LocalDateTime
use the getRevisionDate
method, as shown below.
public class MyRevisionListener
implements RevisionListener {
@Override
public void newRevision(Object revisionEntity) {
MyRevision revision = (MyRevision)revisionEntity;
revision.fixTimezone();
}
}
@Entity
@RevisionEntity (MyRevisionListener.class)
public class MyRevision
implements Serializable {
@Id
@GeneratedValue
@RevisionNumber
private long id;
@RevisionTimestamp
@Temporal (TemporalType.TIMESTAMP)
@Column (nullable = false)
private Date date;
private static final ZoneId ZONE_ID_UTC = ZoneId.of("UTC");
public void fixTimezone() {
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZONE_ID_UTC);
date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
@NotNull
public LocalDateTime getRevisionDate() {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
...
}
Related Hibernate issues:
- https://hibernate.atlassian.net/browse/HHH-10828
- https://hibernate.atlassian.net/browse/HHH-10827
- https://hibernate.atlassian.net/browse/HHH-10496
来源:https://stackoverflow.com/questions/37748142/how-to-save-utc-instead-of-local-timestamps-for-hibernate-envers-revision-info