BaseTimeEntity

반영환·2023년 5월 28일
0

스프링 이모저모

목록 보기
5/12
post-thumbnail

BaseTimeEntity

BaseTimeEntity Abstract Class Define

@Getter
@MappedSuperclass // BaseEntity를 상속한 엔티티들은 아래 필드들을 컬럼으로 인식하게 된다.
@EntityListeners(AuditingEntityListener.class)  // Auditing(자동으로 값 매핑) 기능 추가
public abstract class BaseTimeEntity {

    @CreatedDate
    private LocalDateTime createdTime;

    @LastModifiedDate
    private LocalDateTime lastModifiedTime;
}
  • @MappedSuperclass : JPA Entity 클래스들이 BaseTimeEntity을 상속할 경우 필드들(createdTime, lastModifiedTime)도 컬럼으로 인식하도록 합니다.

  • @EntityListeners(AuditingEntityListener.class) : BaseTimeEntity 클래스에 Auditing 기능을 포함시킵니다.

  • @CreatedDate : Entitiy가 최초로 생성되어 저장될 때 시간이 자동으로 저장됩니다.

  • @LastModifiedDate : 조회한 Entity의 값을 변경할 때 시간이 자동으로 저장됩니다.

Entity Class Extends BaseTimeEntity

@Entity
@AllArgsConstructor
@NoArgsConstructor
public class User extends BaseTimeEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;
    private String password;

    @Builder
    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

@EnableJpaAuditing

@SpringBootApplication
@EnableJpaAuditing
public class ApiPracticeApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiPracticeApplication.class, args);
    }
}
  • @EnableJpaAuditing : JPA Auditing 어노테이션들을 모두 활성화
profile
최고의 오늘을 꿈꾸는 개발자

0개의 댓글