본문 바로가기
★ 프로젝트 + 트러블 슈팅 ★

[DDD 헥사고날 아키텍처] 도메인 -> 엔티티 변환간 baseEntity 내 createdDateTime 초기화 현상 트러블 슈팅

by 리승우 2024. 7. 14.

이슈 내용

1. DDD 구조 (헥사고날 아키텍처)를 통해 엔티티와 도메인을 분리한 상황에서, 게시글 수정 작업이 필요하여 아래 코드를 실행

public void patchPost(Long id, ModifyPostReq modifyPostReq) {
        PostEntity postEntity = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 게시글이 존재하지 않습니다.")
        );
        Post post = postMapper.toDomain(postEntity);
        post.updatedPostInfo(modifyPostReq);
        postEntity = postMapper.toEntity(post);
        postRepository.save(postEntity);
    }

 

2. 위와 같이 실행될 경우, 다시 postEntity로 변환하는 과정이 아래와 같음 (postMapper 사용)

  @Override
      public PostEntity toEntity(Post domain) {
          if ( domain == null ) {
              return null;
          }

        PostEntity.PostEntityBuilder postEntity = PostEntity.builder();

        postEntity.id( domain.getId() );
        postEntity.boardCategory( domain.getBoardCategory() );
        postEntity.userId( domain.getUserId() );
        postEntity.title( domain.getTitle() );
        postEntity.content( domain.getContent() );
        postEntity.image( domain.getImage() );
        postEntity.postCategory( domain.getPostCategory() );
        postEntity.viewCount( domain.getViewCount() );
        postEntity.likesCount( domain.getLikesCount() );
        postEntity.isDeleted( domain.getIsDeleted() );

        return postEntity.build();
    }

 

3. 현재 postEntity는 baseEntity를 상속받고 있으며, 변경 감지를 통해 생성시간, 수정시간이 관리되고 있음

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

    @CreatedDate
    private LocalDateTime createdDateTime;

    @LastModifiedDate
    private LocalDateTime modifiedDateTime;
}

 

4. 해당 과정을 거쳐 postEntity를 확인해보면, 수정시간은 업데이트되어 DB에 반영되고 있으나, 생성시간은 Null로 변경되어 DB에 반영되고 있음

 

해결 과정

1. postEntity로 변환하는 과정 중에, 특정 이슈로 인해 생성시간이 null로 변환되고 있음 (BaseEntity값을 변경함으로써 생기는 것 같음)
=> 보다 정확한 이유를 발견하지 못함...

 

2. 위 이유로, 완벽한 해결방법은 아닐 것 같으나.. 아래와 같이 생성시간은 변경되면 안되는 데이터가 맞으니 BaseEntity단에서 생성시간은 업데이트 되지 않도록 별도 처리함

 

    @CreatedDate
    @Column(name = "created_date_time", updatable = false)
    private LocalDateTime createdDateTime;

 

해당 현상이 발생한 명확한 이유는 파악하지 못했으나,,

생성시간은 변경되지 않는 것이 근본적으로 맞으니 위와 같이 처리함.

 

궁금하네..

댓글