您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關SpringBoot中JPA + AuditingEntityListener時區設置方式是什么,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
在SpringBoot項目中,如果應用啟用了EnableJpaAuditing并且使用AuditingEntityListener對實體的創建時間、更新時間進行自動審計,可能存在生成時間的時區和系統時區不一致的問題。
將時區設定為指定時區:
spring.jpa.properties.hibernate.jdbc.time_zone = GMT+8
源碼
/** * 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上。
源碼
/** * 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> * <persistence-unit-metadata> * <persistence-unit-defaults> * <entity-listeners> * <entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener" /> * </entity-listeners> * </persistence-unit-defaults> * </persistence-unit-metadata> * </pre> * * After that it's just a matter of activating auditing in your Spring config: * * <pre> * @Configuration * @EnableJpaAuditing * class ApplicationConfig { * * } * </pre> * * <pre> * <jpa:auditing auditor-aware-ref="yourAuditorAwarebean" /> * </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發生持久化和更新操作時。
關于SpringBoot中JPA + AuditingEntityListener時區設置方式是什么就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。