일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 구글애널리틱스
- @Query
- db
- SEO
- set
- useEffect
- Thymeleaf
- router
- @Controller
- mergeattributes()
- post
- 워드프레스
- 인텔리제이
- GET
- 데이터베이스
- firebase
- ChatGPT
- GA4
- 구글
- 구글알고리즘
- @Repository
- JPA
- @Entity
- linkedhastset
- HttpSession
- 플러그인
- Polylang
- addallattributes()
- Login
- 리액트오류
- Today
- Total
개발천재
[Spring Boot] 생성일, 수정일 자동관리하기 @EnableJpaAuditing 본문
@EnableJpaAuditing 이해하기
@EnableJpaAuditing은 Spring Data JPA에서 엔티티의 생성일자나 수정일자 등을 자동으로 관리할 수 있게 해주는 기능을 활성화하는 어노테이션이다. 이 어노테이션을 사용하면 @CreatedDate, @LastModifiedDate와 같은 어노테이션을 통해 날짜와 시간을 자동으로 기록할 수 있게 된다.
시간을 자동으로 기록할 수 있어 수동으로 입력할 필요가 없고, 데이터의 생성 및 수정 시점을 쉽게 관리할 수 있어서 기록이 필요한 앱에서 유용하다는 장점이 있다.
또한 @EnableJpaAuditing은 날짜 관리 외에도 @CreatedBy, @LastModifiedBy와 같은 기능을 통해 자동으로 작성자나 수정자를 기록할 수도 있다.
@EnableJpaAuditing의 주요 역할
엔티티의 생성일자(@CreatedDate)와 수정일자(@LastModifiedDate)를 자동으로 관리하도록 도와준다. 자동으로 현재 시간을 설정할 수 있어서, 데이터베이스에 삽입될 때 또는 수정될 때마다 날짜와 시간이 기록된다.
사용 방법
@EnableJpaAuditing을 설정 클래스(main이 있는 곳)에 추가한다. 이 애너테이션이 있어야 JPA Auditing 기능이 활성화되고, 자동으로 날짜가 삽입될 수 있다.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing // JPA Auditing 기능 활성화
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
엔티티 클래스에서 @CreatedDate 또는 @LastModifiedDate를 사용하여 날짜 자동 입력을 설정한다.
@CreatedDate는 생성 시 날짜.
@LastModifiedDate는 수정 시 날짜.
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import java.time.LocalDateTime;
@Entity
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@CreatedDate
private LocalDateTime createdDate; // 자동으로 생성일자 입력
@LastModifiedDate
private LocalDateTime lastModifiedDate; // 자동으로 수정일자 입력
}
@EnableJpaAuditing 주요 기능
엔티티 생성 시: @CreatedDate를 통해 생성된 날짜를 자동으로 삽입.
엔티티 수정 시: @LastModifiedDate를 통해 수정된 날짜를 자동으로 업데이트.
LocalDateTime 또는 LocalDate 타입으로 날짜를 저장할 수 있다.
'개발 준비 > Spring Boot' 카테고리의 다른 글
[Spring Boot] Thymeleaf, 반복문에서 index 보여주기, stat (2) | 2025.02.21 |
---|---|
[Spring Boot] HttpSession으로 로그인 구현하기 (2) | 2025.02.20 |
[Spring Boot] WebMvcConfigurer 이해하기 (1) | 2025.02.19 |
[Spring Boot] Validation, 검증하기 (2) | 2025.02.18 |
[Spring Boot] Bean을 정의하는 어노테이션 (1) | 2025.02.18 |