개발/부트캠프

본캠프 : BaseEntity 사용

EJ EJ 2025. 3. 2. 14:03

1. common 패키지에 entity 패키지 추가 후 BaseEntity 클래스 생성

 

2. BaseEntity 클래스 작성

ex)

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {

    @CreatedDate
    @Column(updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private LocalDateTime updatedAt;
}

 

3. domain - entity 클래스에서 상속

ex) 

@Getter
@Entity
@NoArgsConstructor
@Table(name = "members")
public class Member extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String email;

    private String password;
    private String name;

    public Member(String email, String password, String name) {
        this.email = email;
        this.password = password;
        this.name = name;
    }
@Getter
@Entity
@NoArgsConstructor
@Table(name = "todos")
public class Todo extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String content;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "member_id", nullable = false)
    private Member member;

    public Todo(String content, Member member) {
        this.content = content;
        this.member = member;
    }

 

4. Application에서 @EnableJpaAuditing 설정

* @EnableJpaAuditing : Spring Data JPA에서는 엔터티(Entity)에 생성일, 수정일을 자동으로 기록하는 감사(Auditing) 기능을 제공한다.

@EnableJpaAuditing
@SpringBootApplication
public class BasicTodoTestApplication {

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

}

 

5. responseDto에 적용

ex) 

@Getter
public class TodoSaveResponseDto {

    private final Long id;
    private final Long memberId;
    private final String memberName;
    private final String content;
    private final LocalDateTime createdAt;
    private final LocalDateTime updatedAt;

    public TodoSaveResponseDto(Long id, Long memberId, String memberName, String content, LocalDateTime createdAt, LocalDateTime updatedAt) {
        this.id = id;
        this.memberId = memberId;
        this.memberName = memberName;
        this.content = content;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt;
    }

}
@Getter
public class TodoUpdateResponsetDto {

    private final String content;
    private final LocalDateTime createdAt;
    private final LocalDateTime updatedAt;


    public TodoUpdateResponsetDto(String content, LocalDateTime createdAt, LocalDateTime updatedAt) {
        this.content = content;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt;
    }
    
}

 

끝!