JPA를 활용할 때 게시글의 작성자,수정자 아이디를 자동적으로 세팅해주고 싶은 경우가 있어요.
비즈니스 로직단에서 일일이 세팅하는 수고를 덜어주죠.
이 예제에서는 알아보기 쉽도록 아주 기본만 작성하였습니다.
AuditorAwareConfig
소스 설명 드릴게요.
UserInfo는 세션 아이디를 담아둔 객체입니다.
테이블에 넣어줄 로그인 사용자 ID를 Optional 클래스에 세팅하여 리턴하면 끝입니다.
AuditorAware를 구현할 때 대부분의 예제에서는 별도의 클래스를 만들어서 임포트 받지만 여기서는 최대한 간단해보이도록 한 소스 파일에 직접 구현했습니다.
@Resource private UserInfo userInfo;
Long userId = userInfo.getIdIsLogin();
로그인 체크하고 로그인 아이디 가져오는 부분을 직접 개발하시면 됩니다.
사용자 아이디가 Long 타입이 아니면 다른 타입으로 바꿔주면 됩니다.
@EnableJpaAuditing
@Configuration
public class AuditorAwareConfig {
@Resource
private UserInfo userInfo;
@Bean
public AuditorAware<Long> auditorAware() {
return new AuditorAware<>() {
@Override
public Optional<Long> getCurrentAuditor() {
Long userId = userInfo.getIdIsLogin();
return Optional.of(userId);
}
};
}
}
BoardEntity
이제 사용만 하면 됩니다.
우선, BoardEntity에 @EntityListeners를 설정해주세요.
그리고 등록자에 @CreatedBy 어노테이션을 붙여주고,
수정자에는 @LastModifiedBy 어노테이션을 붙여주면 됩니다.
org.springframework.data.annotation.CreatedBy
org.springframework.data.annotation.LastModifiedBy
@Entity
@Table(name = "board")
@Getter
@Setter
@EntityListeners(AuditingEntityListener.class)
public class BoardEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long boardId;
@Column(length = 100)
private String title;
@Column(length = 4000)
private String content;
@CreatedBy
@Column(updatable = false)
private Long regBy;
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime regDt;
@LastModifiedBy
private Long updBy;
@UpdateTimestamp
private LocalDateTime updDt;
}
'Backend > Spring' 카테고리의 다른 글
Spring Boot Validation Custom (ConstraintValidator) (0) | 2019.11.19 |
---|---|
Spring Boot Querydsl (Maven, Gradle 5) (0) | 2019.11.15 |
JPA @ManyToOne Join (Only JpaRepository) (0) | 2019.11.11 |
Spring Boot Interceptor 적용 (0) | 2019.10.16 |
Spring Boot Session MySQL 연동, 저장 (1) | 2019.10.16 |