본문 바로가기
hibernate, JPA

Embeddable 객체의 필드가 모두 null인 경우 인스턴스화 하지 못하는 이슈

by 무늬 2023. 6. 26.

문제 상황

객체를 생성하고 업데이트하는 로직에서 NulPointException이 발생했다. 정확히는 업데이트를 위한 조회 과정에서 예외가 발생했다.

 

원인

특정 객체의 embeddable 객체의 필드가 모두 null인 경우 hibernate는 객체의 필드뿐만 아니라 객체 자체를 null로 반환한다고 한다. 해당 객체는 non-null이었기에 조회과정에서 예외가 발생했다.

 

해결방법 1

Embedded 객체에 null을 허용한다.

 

해결방법 2

Embedded 객체에 non-null 필드를 추가한다.

 

해결방법 3

hibernate.create_empty_composites.enabled

hibernate 가이드 문서에서 이 옵션을 키면 가능하다고 한다. 하지만 실험적 기능으로 운영 환경에서 사용을 권장하지 않는다고 하니 패스한다.

 

https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#_misc_options

 

Hibernate ORM 5.6.15.Final User Guide

Fetching, essentially, is the process of grabbing data from the database and making it available to the application. Tuning how an application does fetching is one of the biggest factors in determining how an application will perform. Fetching too much dat

docs.jboss.org

 

 

결과

단순히 위의 현상을 해결할 수는 있지만 좀 더 근본적인 원인을 살펴보면, Embedded 객체의 모든 필드가 null인 이유는 Embedded 객체와 Embedded 객체를 필드로 가진 객체의 생성시점이 다르기 때문이다. 때문에 두 객체를 결합하지 않고 분리하는 것이 더 적절한 선택이다.