Jpa, Fetchtype.Lazy 오류

개발개발·2021년 6월 17일
0

JPA를 사용하던 중 아래와 같은 오류가 생겼다.

No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.HashMap["result2"]->java.util.ArrayList[0]->com.example.demo.entity.RecipesEntity["firstCategoryEntity"]->com.example.demo.entity.FirstCategoryEntity$HibernateProxy$5HcjtMZD["hibernateLazyInitializer"])

public class RecipesEntity {

    private int id;
    private String title;
 
    private FirstCategoryEntity firstCategoryEntity;
    private SecondCategoryEntity secondCategoryEntity;


    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getId() {return id;}

    public void setId(int id) {this.id = id;}

    @Basic
    @Column(name = "title")
    public String getTitle() {return title;}

    public void setTitle(String title) {this.title = title;}

    @OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    @JoinColumn(name = "first_category_id")
    public FirstCategoryEntity getFirstCategoryEntity() { return firstCategoryEntity; }
    public void setFirstCategoryEntity(FirstCategoryEntity firstCategoryEntity) { this.firstCategoryEntity = firstCategoryEntity; }

    @OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    @JoinColumn(name = "second_category_id")
    public SecondCategoryEntity getSecondCategoryEntity() { return secondCategoryEntity; }
    public void setSecondCategoryEntity(SecondCategoryEntity secondCategoryEntity) { this.secondCategoryEntity = secondCategoryEntity; }

}

lazy fetch는 db에서 관련된 내용을 가져올때 바로 가져오는 것이 아니라 호출될때 불러오는 방식이다. 이때 내용을 직렬화에 실패서 나오는 오류다.

해결방법 3가지
1. jackson.serialization.fail-on-empty-beans=false
설정을 통해서 직렬화 설정을 한다. 안그래도 dto <-> entity등 변환하면서 매번 새롭게 ObjectMapper를 사용했는데 이 방법을 사용하면 프론트에서 데이터를 받고 변환하는 것이 더 수월해질 것 같다. 다만 오류를 무시하는 만큼 다른 곳에서 문제가 생길수 있을 것 같다.
2. FetchType.LAZY 지우기
3. @JsonIgnore로 직렬화에서 배제하기

reference
https://jhkang-tech.tistory.com/92

profile
청포도루이보스민트티

0개의 댓글