ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JPA] No default constructor for entity(에러)
    JPA 2023. 9. 7. 21:01
    728x90

    안녕하세요.

    요즘 공부하느라 비공개 글만 올리다가 오랜만에 이렇게 공개글을 올립니다.

     

    요즘 회사에서 SpringBoot 프로젝트를 간단하게 하나 하고있는데 아주 재밌네요~

     

    아그러나 이건 회사랑 관련 된건 아니고 제 개인 토이 프로젝트 진행중에 발견한 에러를 해결해 보고자 합니다.

    그러다가 발견한 오류를 기록해 보고자 합니다.

     

    오류 발생 상황

    오류 발생 상황은 Member Entity에 @Embedded 돼있는 Address가 있습니다.

    @Embeddable
    @Getter
    public class Address {
        private String street;
        private String city;
        private String zipcode;
    
        public Address(String street, String city, String zipcode) {
            this.street = street;
            this.city = city;
            this.zipcode = zipcode;
        }
    }

    Address의 구성입니다. Member에 넣기전에 생성자를 통해 객체를 생성 후 Member에 추가할 계획입니다.

    진행시에는 따로 문제가 없었으나 JPA를 통한 저장 부분에서 에러가 발생했습니다.

     

    에러 발생

    com.bookreport.core.domain.Address; nested exception is org.hibernate.InstantiationException: No default constructor for entity:

     

    위와 같은 오류로 저장이 되지 않았습니다.

    에러 내용을 읽어보니 기본 생성자가 없다는걸로 보여집니다.

     

    이제 해당 에러를 해결해 보겠습니다.

     

    해결

    해결 방법은 의외로 간단합니다. lombok을 사용하신다는 가정하에

    Address Class에 @NoArgsConstructor Annotation을 추가해 주시면 됩니다.

     

    @Embeddable
    @Getter
    @NoArgsConstructor
    public class Address {
        private String street;
        private String city;
        private String zipcode;
    
        public Address(String street, String city, String zipcode) {
            this.street = street;
            this.city = city;
            this.zipcode = zipcode;
        }
    }

    @NoArgsConstructor의 기능은 파라미터가 없는 기본 생성자 생성!

     

    입니다.

     

    혹은

    @Embeddable
    @Getter
    public class Address {
        private String street;
        private String city;
        private String zipcode;
    
        protected Address(){
    
        }
    
        public Address(String street, String city, String zipcode) {
            this.street = street;
            this.city = city;
            this.zipcode = zipcode;
        }
    }

    이런식으로 만들어주는것도 하나의 방법입니다.

     

    해당 방법 같은 경우에는 Address address=new Address() 

    이런식으로 사용 못하게 막아 builder 패턴으로 사용하도록 규칙을 정해 줄 수 있다는 장점이 있습니다.

    (누구는 빌터패턴으로... 누구는 address.set~ 이런식으로 규칙없이 만드는걸 막아줍니다!)

     

    까먹지 않고 다음에 잘 활용해 보도록 하겠습니다. ~:D

     

    이렇게 간단한 오류 하나하나씩 기록해 나가면서 까먹지 않고 더 발전해 보고자 합니다.

     

    감사합니다!😊😊

     

    댓글

Designed by Tistory.