How to save UTC (instead of local) timestamps for Hibernate Envers revision info?

杀马特。学长 韩版系。学妹 提交于 2019-12-12 00:12:05

问题


Using Hibernate/Envers, how to:

  1. Save UTC (instead of local) timestamps for Hibernate Envers revision info?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!