/* * Copyright 2008-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.jpa.domain.support; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.data.auditing.AuditingHandler; import org.springframework.data.domain.Auditable; import org.springframework.util.Assert; /** * 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 * @author Christoph Strobl */ @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) { Assert.notNull(target, "Entity must not be null!"); 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) { Assert.notNull(target, "Entity must not be null!"); if (handler != null) { handler.getObject().markModified(target); } } }