Spring JPA Auditing 이란?
JPA 로 Entity를 만들다 보면, 공통적으로 사용하는 필드들이 필요하다.
각 Entity 마다 컬럼을 추가하고, 생성자에 넣어주고~~~ 이 과정들을 N번 반복해야하는데, 이를 추상화 하면 한번에
공통된 컬럼을 사용할 수 있다. 주로, 생성일, 수정일 ,작성자, 수정자 와 같은 정보는 중요하기 때문에 기록을 잘 남겨놓는것이 매우 중요하다.
따라서, JPA 에서는 Audit이라는 기능을 제공하고, Spring Data JPA에서 자동으로 값을 넣어주는 기능을 해주기 때문에
매우 간편하게 데이터를 관리 할 수 있다.
MyBatis 로 작업할때는 하나하나 upadate ,insert를 해줘야 해서 매우 까다로웠음;;
1. Application.java 에 @EnableJpaAuditing 붙이기
@EnableJpaAuditing 어노테이션을 붙여야 Auditing 기능을 사용한다고 알려 줄 수 있다.
@EnableJpaAuditing
@SpringBootApplication
public class MenoApplication {
public static void main(String[] args) {
SpringApplication.run(MenoApplication.class, args);
}
}
2. 공통된 필드 추상화 하기
@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Timestamped {
@CreatedDate
@Column(updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime createdAt;
@LastModifiedDate
@Column
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime modifiedAt;
}
- @MappedSuperclass : JPA Entity에서 상속을 위한 어노테이션
- @EntityListeners(AuditingEntityListener.class): 해당 클래스에 Auditing 기능을 포함하기 위한 어노테이션
- @CreatedData: Entity가 생성될때 시간이 자동 저장 @Colum(updatable = false) 업데이트를 하지 않겠다.
- @LastModifiedData: 조회한 Entity의 값을 변동할 때 시간이 자동 저장
JPA 가 위 어노테이션들을 통해, 업데이트 되거나 새로 생성될때 자동으로 데이터를 넣어 준다.
3. Entity 에 상속받기
상속을 통해 수정날짜, 생성날짜에 대한 정보를 받아올 수 있다.
@Entity // JPA가 관리할 수 있는 Entity 클래스 지정
@Getter
@Setter
@Table(name = "memo") // 매핑할 테이블의 이름을 지정
@NoArgsConstructor
public class Memo extends Timestamped {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username", nullable = false)
private String username;
@Column(name = "contents", nullable = false, length = 500)
private String contents;
public Memo(MemoRequestDto requestDto) {
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
}
public void update(MemoRequestDto requestDto) {
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
}
}
4. ResponseDto 에도 추상화된 컬럼 추가하기
@Getter
public class MemoResponseDto {
private Long id;
private String username;
private String contents;
private LocalDateTime createdAt;
private LocalDateTime modifiedAt;
public MemoResponseDto(Memo memo) {
this.id= memo.getId();
this.username=memo.getUsername();
this.contents=memo.getContents();
this.createdAt = memo.getCreatedAt();
this.modifiedAt = memo.getModifiedAt();
}
}
5. QueryMethod 로 List 조회해 보기
Repository
public interface MemoRepository extends JpaRepository<Memo,Long> {
List<Memo> findAllByOrderByModifiedAtDesc();
}
Service
// Service 에서 가장 최신에 수정된 글 목록 조회
public List<MemoResponseDto> getMemos() {
return memoRepository.findAllByOrderByModifiedAtDesc().stream().map(MemoResponseDto::new).toList();
}
QueryMethod는 정해진 규칙에 맞게끔 query를 조회 할 수 있다.
JPA의 가장 큰 장점이자 매우 편리한 기능이다.
추상화된 컬럼(수정 날짜)을 내림차순으로 조회하는 query 를 조회할 수 있다.
마무리
Spring JPA 강의를 여러번 들으면서 Auditing이라는 개념을 처음 들어봤다.
abstract를 활용해서 재사용성을 고려해서 구현해 봤다는 것! 이 의미 있었고, 오늘 배운내용준 가장 알차다 생각했다.
클린 코드에 한발짝 다가 갈 수 있는 기능👍
⭐⭐⭐ 자주 사용될것 같아서 확실하게 기억해 두기!
'Programing > Spring' 카테고리의 다른 글
Redis 개념과 사용법 알아보기 (0) | 2025.03.05 |
---|---|
Spring Cloud 학습 (0) | 2025.02.12 |
Spring JPA 관계 이해하기 (0) | 2025.02.07 |
Spring Bean 수동 등록하기 + 같은 타입의 Bean이 여러개 라면? (1) | 2025.02.05 |