디자인너 코딩하기

Entity Listener - ② 본문

spring/Entity

Entity Listener - ②

designercoding 2022. 4. 19. 10:44

방법

2. Spring Jpa에서 제공하는 기본 Entity Listener

메인 클래스에 @EnableJpaAuditing 붙여준다.

@SpringBootApplication
@EnableJpaAuditing
public class BookmanagerApplication {

  public static void main(String[] args) {
    SpringApplication.run(BookmanagerApplication.class, args);
  }

}

 

해당 Entity에 @EntityListeners(value= AuditingEntityListener.class) 붙여준다.

 

해당 필드에 맞는 어노테이션을 붙여준다.

(@CreatedDate, @LastModifiedDate ...)

@NoArgsConstructor
@Data
@Entity
@EntityListeners(value= {AuditingEntityListener.class, UserEntityListener.class})
public class User {

  @Id
  @GeneratedValue
  private Long id;
  private String name;
  private String email;
  
  @CreatedDate
  private LocalDateTime createdAt;
  
  @LastModifiedDate
  private LocalDateTime updatedAt;

}

 


방법

2. Spring Jpa에서 제공하는 기본 Entity Listener 심화

현업에서 쓰이는 방법

 

위에 방법에서 Entity의 공통으로 반복적으로 쓰이는 부분을 클래스를 따로 만들어 한번만 쓰일 수 있도로 리팩터링

  @CreatedDate
  private LocalDateTime createdAt;

  @LastModifiedDate
  private LocalDateTime updatedAt;

 

import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;

@Data
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
public class BaseEntity  implements Auditable {

  @CreatedDate
  private LocalDateTime createdAt;

  @LastModifiedDate
  private LocalDateTime updatedAt;

}

@MappedSuperclass

해당 클래스 필드를 상속받는 entity 컬럼에 포함시킨다.

 

즉 아래와 같이 created_at과 updated_at의 반복 코드를 제거했고 @EntityListeners도 제게 되었다.

@NoArgsConstructor
@Data
@Entity
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class Book extends BaseEntity  implements Auditable {
  @Id
  @GeneratedValue
  private Long id;
  private String name;
  private String author;
}

@ToString(callSuper = true) / @EqualsAndHashCode(callSuper = true)

상속받는 슈퍼클래스의 정보를 tostring / EqualsAndHashCode에 포함되도록 지정

→ AuditingEntityListener 작동하기 위해

→ 사용하지 않으면 값이 안 나오고 @Data에 warning이 표시된다.

반응형

'spring > Entity' 카테고리의 다른 글

SprignBoot H2DB 설정  (0) 2022.04.21
Entity Listener - ①  (0) 2022.04.19
Entity  (0) 2022.04.18