Skip to main content Link Menu Expand (external link) Document Search Copy Copied

JPA BaseEntity Auditing ์ ์šฉ

Table of contents

  1. @EnableJpaAuditing ์ ์šฉ
  2. BaseEntity ์ƒ์„ฑ
  3. ๋ฆฌ๋ทฐ Entity์— ์ ์šฉ


@EnableJpaAuditing ์ ์šฉ


โ€˜์ƒ์„ฑ์ผ์žโ€™, โ€˜๋ณ€๊ฒฝ์ผ์žโ€™ ์™€ ๊ฐ™์€ ๋ˆ„๊ฐ€, ์–ธ์ œ ๋ฐ์ดํ„ฐ๋ฅผ ์ƒ์„ฑํ–ˆ๊ณ  ๋ณ€๊ฒฝํ–ˆ๋Š”์ง€์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ๋Š” ์—”ํ‹ฐํ‹ฐ์— ๊ณตํ†ต์ ์œผ๋กœ ๋งŽ์ด ์‚ฌ์šฉ๋œ๋‹ค.

์ด๋Ÿฌํ•œ ๊ฐ’์„ ์ž๋™์œผ๋กœ ๋„ฃ์–ด์ฃผ๋Š” ๊ธฐ๋Šฅ์„ JPA๋Š” ์ œ๊ณตํ•œ๋‹ค.


@SpringBootApplication
@EnableJpaAuditing

@SpringBootApplication ์ด ์žˆ๋Š” ํด๋ž˜์Šค์— @EnableJpaAuditing ์–ด๋…ธํ…Œ์ด์…˜์„ ์ถ”๊ฐ€ํ•˜๋ฉด ๋œ๋‹ค.

์œ„์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์€ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ ์ž‘์„ฑ ์‹œ, ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ํด๋ž˜์Šค๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ณผ์ •์—์„œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค.


@Configuration
@EnableJpaAuditing
public class JpaAuditingConfiguration{

}

์œ„์™€ ๊ฐ™์ด Configuration ํด๋ž˜์Šค๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.


BaseEntity ์ƒ์„ฑ

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

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime updatedAt;
            
}
  • @MappedSuperclass : ์ƒ์†๋ฐ›๋Š” ์—”ํ‹ฐํ‹ฐ ํด๋ž˜์Šค์— ๋งคํ•‘ ์ •๋ณด๋ฅผ ์ „๋‹ฌ

  • @EntityListeners : ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ ์šฉํ•˜๊ธฐ ์ „ ํ›„๋กœ ์ฝœ๋ฐฑ์„ ์š”์ฒญ

  • AuditingEntityListener : ์—”ํ‹ฐํ‹ฐ์˜ Auditing ์ •๋ณด๋ฅผ ์ฃผ์ž…ํ•˜๋Š” JPA ์—”ํ‹ฐํ‹ฐ ๋ฆฌ์Šค๋„ˆ ํด๋ž˜์Šค

  • @CreatedDate : ๋ฐ์ดํ„ฐ ์ƒ์„ฑ ๋‚ ์งœ ์ž๋™์œผ๋กœ ์ฃผ์ž…

  • @LastModifiedDate : ๋ฐ์ดํ„ฐ ์ˆ˜์ • ๋‚ ์งœ ์ž๋™์œผ๋กœ ์ฃผ์ž…


๋ฆฌ๋ทฐ Entity์— ์ ์šฉ

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString(callSuper = true)
public class Review extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "review_id")
    private Long id;

    @Column(nullable = false)
    private String title;
    @Column(nullable = false, length = 500)
    private String content;
    @Column(name = "user_id", nullable = false)
    private String userId;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "hospital_id")
    private Hospital hospital;

    public Review(ReviewCreateRequest reviewCreateRequest,Hospital hospital) {
        this.title = reviewCreateRequest.getTitle();
        this.content = reviewCreateRequest.getContent();
        this.userId = reviewCreateRequest.getUserId();
        this.hospital = hospital;
    }
}
  • callSuper = true ๋ถ€๋ชจ ํด๋ž˜์Šค ํ•„๋“œ ํฌํ•จํ•˜๋Š” ์—ญํ•  ์ˆ˜ํ–‰


image-20221208114816833

๋ฆฌ๋ทฐ DB ๋“ฑ๋ก ์‹œ ์ž˜ ์ ์šฉ๋˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.