테이블에 CRUD 작업을 해야 할 떄 생성일자, 변경일자, 등록자, 수정자 필드에 작업은 공통으로 적용이 되는 작업 입니다. JPA를 적용 할 때 @EntityListeners 에노테이션을 사용 하면 쉽게 적용 할 수 있습니다.
테이블에 CRUD 작업을 해야 할 떄 생성일자, 변경일자, 등록자, 수정자 필드에 작업은 공통으로 적용이 되는 작업 입니다. JPA를 적용 할 때 @EntityListeners 에노테이션을 사용 하면 쉽게 적용 할 수 있습니다. @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
과 같이 작성되어 있습니다. Spring-Data-Jpa에서 제공 하는 기본 에노테이션을 사용하여 생성 일자와 수정일자를 코드 개발 없이 사용 할 수 있습니다. 다음은 코드 개발 없이 적용 할 수 있는 코드 입니다
- 요구 사항 : TB_EVENT_DEMO 테이블에 신규 등록시 자동으로 생성일자에 날짜를 적용하고 테이블의 내용이 변경이 되면 자동으로 수정 일자를 적용해야 한다.
// Entity에 적용할 공통 기능 @EntityListeners(AuditingEntityListener.class)publicclassAuditVO {// create_Date_Time 컬럼, insert 적용, update 불가 @CreatedDate @Column(updatable =false)privateLocalDateTime createDateTime; // update_date_time 컬럼, insert 적용, update 적용 @LastModifiedDateprivateLocalDateTime updateDataTime;}// TB_EVENT_DEMO 테이블 // AuditVO를 확장 하여 DemoEventEntity에 정의된 컬럼 외 // create_Date_Time, update_date_time 컬럼 추가 @Table(name ="TB_EVENT_DEMO")@EntitypublicclassDemoEventEntityextendsAuditVO { @Id @GeneratedValue(strategy =GenerationType.SEQUENCE)privateint id;privateString title;privateString content;privateString name;}// Spring-Data-Jpa에서 제공하는 Auditing기능 활성화 @EnableJpaAuditing@SpringBootApplication()publicclassJpaServiceApplication {publicstaticvoidmain(String[] args) {SpringApplication.run(JpaServiceApplication.class, args); }}
@EnableJpaAuditing 선언으로 Auditing 기능이 활성화(: JpaAuditingRegistrar )되고 Entity에 적용된 @EntityListeners에 지정한 클래스 AuditingEntityListener.class에 의해서 Entity에 작업이 발생 하면 리스너기 작동을 히여 지정한 형식으로 적용이 되어 요구 사항에 만족 하는 코드가 됩니다.
AuditingEntityListener 클래스는 AuditingHandler에 등록된 값을 이용해서 @PrePersist, @PreUpdate가 작동 될 떄 해당 값을 설정 하도록 하는 기능 입니다.
@ConfigurablepublicclassAuditingEntityListener {private @NullableObjectFactory<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}. */publicvoidsetAuditingHandler(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 */ @PrePersistpublicvoidtouchForCreate(Object target) {Assert.notNull(target,"Entity must not be null");if (handler !=null) {AuditingHandler object =handler.getObject();if (object !=null) {object.markCreated(target); } } } /** * Sets modification and creation date and auditor on the target object in case it implements {@link Auditable} on * update events. * * @param target */ @PreUpdatepublicvoidtouchForUpdate(Object target) {Assert.notNull(target,"Entity must not be null");if (handler !=null) {AuditingHandler object =handler.getObject();if (object !=null) {object.markModified(target); } } }}
만약 생성자와 수정자 등을 추가 해서 로그인 사용자 또는 작업자를 관리 해야 하는 요구 사항이 추가 되면 AuditingHandler에 등록 해서 사용 해야 한다는 것을 알 수 있습니다. 아래는 AuditingHandler의 일부 코드 입니다. AuditorAware<?> 라는 맴버 변수를 가지고 있고 해당 값애 추가 하도록 되어 있습니다.