Avoid Jackson serialization on non fetched lazy objects

前端 未结 14 2010
终归单人心
终归单人心 2020-11-22 13:02

I have a simple controller that return a User object, this user have a attribute coordinates that have the hibernate property FetchType.LAZY.

When I try to get this

14条回答
  •  不知归路
    2020-11-22 13:35

    I've spent whole day trying to solve the same problem. You can do it without changing existing message converters configuration.

    In my opinion the easiest way to solve this problem only with 2 steps with help of jackson-datatype-hibernate:

    kotlin example (same as java):

    1. Add In build.gradle.kts:
    implementation("com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:$jacksonHibernate")
    
    1. Create @Bean
       @Bean
       fun hibernate5Module(): Module = Hibernate5Module()
    

    • Notice that Module is com.fasterxml.jackson.databind.Module, not java.util.Module

    • Also good practice is to add @JsonBackReference & @JsonManagedReference to @OneToMany & @ManyToOne relationships. @JsonBackReference could be only 1 in class.

提交回复
热议问题