Spring Boot JPA Lazy Fetch is not working

前端 未结 2 1486
一向
一向 2021-01-19 17:38

I have following two domain objects Suggestion and UserProfile

They are mapped with each other in one to many relationship. When I fetch all suggestions using Spring

相关标签:
2条回答
  • 2021-01-19 17:39

    You can use @JsonManagedReference & @JsonBackReference to prevent proxy call by jakson. Following code may help you.

    @JsonBackReference
    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    private Set<Suggestion> suggestions;
    
    @JsonManagedReference
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "suggestion_by")
    private UserProfile user;
    

    Add the following dependency, change version according to your hibernate

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-hibernate5</artifactId>
    </dependency>
    

    and finally add a new config

    @Configuration
    public class JacksonConfig {
    
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
                jacksonObjectMapperBuilder.modules(new Hibernate5Module());
            }
    
        };
     }
    }
    
    0 讨论(0)
  • 2021-01-19 17:44

    when you declare fetch = FetchType.LAZY, it means hibernate create a proxy for this field in runtime. when getter of this field is called. the hibernate executes another select to fetch this object. in case of your problem getter of "user" field is called by Jackson (if you use rest). so if you don't want "user", try using a model mapper framework (dozer mapper is a good framework).

    0 讨论(0)
提交回复
热议问题