SpringBoot:JPA + AuditingEntityListener時區設置方式

JPA + AuditingEntityListener時區設置

在SpringBoot項目中,如果應用啟用瞭EnableJpaAuditing並且使用AuditingEntityListener對實體的創建時間、更新時間進行自動審計,可能存在生成時間的時區和系統時區不一致的問題。

可在應用配置中添加如下配置

將時區設定為指定時區:

spring.jpa.properties.hibernate.jdbc.time_zone = GMT+8

@EntityListeners(AuditingEntityListener.class)介紹

@EntityListeners

源碼

/**
 * Specifies the callback listener classes to be used for an
 * entity or mapped superclass. This annotation may be applied
 * to an entity class or mapped superclass.
 *
 * @since Java Persistence 1.0
 */
@Target({TYPE})
@Retention(RUNTIME)
public @interface EntityListeners {
    /** The callback listener classes */
    Class[] value();
}

分析

從源碼的註釋中可以很清楚的瞭解到該註解的作用,簡單翻譯如下:該註解用於指定Entity或者superclass上的回調監聽類。該註解可以用於Entity或者superclass上。

AuditingEntityListener.class

源碼

/**
 * JPA entity listener to capture auditing information on persiting and updating entities. To get this one flying be
 * sure you configure it as entity listener in your {@code orm.xml} as follows:
 * 
 * <pre>
 * &lt;persistence-unit-metadata&gt;
 *     &lt;persistence-unit-defaults&gt;
 *         &lt;entity-listeners&gt;
 *             &lt;entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener" /&gt;
 *         &lt;/entity-listeners&gt;
 *     &lt;/persistence-unit-defaults&gt;
 * &lt;/persistence-unit-metadata&gt;
 * </pre>
 * 
 * After that it's just a matter of activating auditing in your Spring config:
 * 
 * <pre>
 * @Configuration
 * @EnableJpaAuditing
 * class ApplicationConfig {
 * 
 * }
 * </pre>
 * 
 * <pre>
 * &lt;jpa:auditing auditor-aware-ref="yourAuditorAwarebean" /&gt;
 * </pre>
 * 
 * @author Oliver Gierke
 * @author Thomas Darimont
 */
@Configurable
public class AuditingEntityListener {
 private ObjectFactory<AuditingHandler> handler;
 /**
  * Configures the {@link AuditingHandler} to be used to set the current auditor on the domain types touched.
  * 
  * @param auditingHandler must not be {@literal null}.
  */
 public void setAuditingHandler(ObjectFactory<AuditingHandler> auditingHandler) {
  Assert.notNull(auditingHandler, "AuditingHandler must not be null!");
  this.handler = auditingHandler;
 }
 /**
  * Sets modification and creation date and auditor on the target object in case it implements {@link Auditable} on
  * persist events.
  * 
  * @param target
  */
 @PrePersist
 public void touchForCreate(Object target) {
  if (handler != null) {
   handler.getObject().markCreated(target);
  }
 }
 /**
  * Sets modification and creation date and auditor on the target object in case it implements {@link Auditable} on
  * update events.
  * 
  * @param target
  */
 @PreUpdate
 public void touchForUpdate(Object target) {
  if (handler != null) {
   handler.getObject().markModified(target);
  }
 }
}

分析

同樣的從該類的註釋也可以瞭解到該類的作用:這是一個JPA Entity Listener,用於捕獲監聽信息,當Entity發生持久化和更新操作時。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: