로직 구성
- 부모 Entity가 생성이 되는 로직에서 자식 Entity가 동시에 생성이 되는 로직
- 여기서 자식 Entity는 3개의 복합키를 가지고 있는 Entity이다
// 부모
... 이상 생략
starScoreService.giveCommentScore(reviewResult, userResult, result, score)
commentRepository.save(result)
... 이하 생략
// 자식
@Transactional
fun giveCommentScore(review: Review, user: User, comment: Comment, starScore:Float){
val result = StarScore.create(user, review, comment, starScore)
starScoreRepository.save(result)
}
문제 발생
- 부모 Entity가 id 값이 0인 Entity를 찾는 문제가 발생
- StarScoreId라는 아이디 생성 클래스를 사용하고 있기 때문에 0을 조회 할 수 있다고 판단 하여 우선 다음 문제를 보기 위해서 아래와 같이 작업하고 다음 애러를 찾았다
@IdClass(StarScoreId::class)
@Entity
@Table(name = "star_score")
class StarScore(
@Id
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="user_id", nullable = false)
val user: User,
@Id
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="review_id", nullable = false)
val review: Review,
@Id
@OneToOne(fetch = FetchType.LAZY)
@NotFound(action = NotFoundAction.IGNORE) // NotFound Annotation으로 오류 무시
@JoinColumn(name="comment_id", nullable = false)
val comment: Comment,
@Column(name = "score", nullable = false)
var score: Float,
)
- attempted to assign id from null one-to-one property 애러 발생
- 해당 애러는 1:1 맵핑 관계에서 부모 Entity가 자꾸 ID에 null을 참조하려는 문제이다
- 근본 적인 원인은 comment Entity 가 생성 되는 과정에서 star_score entity가 동시에 생성이 되는데 이 때 부모 entity의 생성 사항이 자식 entity까지 영향이 가면서 발생한 현상이라는 것을 확인했다
- 따라서 @OneToOne Annotation에 cascode 타입을 Merge로 변경하여 부모 생성 후에 자식이 생성 할 경우 바로 병합 할 수 있게끔 조치했다
@Id
@OneToOne(fetch = FetchType.LAZY, cascade = [CascadeType.MERGE])
@JoinColumn(name="comment_id", nullable = false)
val comment: Comment,
- 이 후 정상 작동 실행 확인했다
- 결론
- 1:1 맵핑 관계에서는 부모 Entity와 자식 Entity간의 종속 관계를 잘 설정해야 한다
'Kotlin > Spring' 카테고리의 다른 글
(Spring) Type mismatch: inferred type is Duration but TemporalAmount! was expected 애러 해결 (0) | 2024.06.05 |
---|---|
(Spring) HTTP 프로젝트 HTTPS로 업그레이드 하기 (0) | 2024.05.31 |
(Spring) FATAL: Max client connections reached 애러 해결 (0) | 2024.05.28 |
(Spring) 사용자 관리를 손쉽게!! Spring Security의 구조를 알아보자!! (0) | 2024.05.22 |
(Spring) LoggingFailureAnalysisReporter 애러 해결 방법 (0) | 2024.05.17 |