Avoid Jackson serialization on non fetched lazy objects

前端 未结 14 1908
终归单人心
终归单人心 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:32

    I made a very simple solution to this problem.

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    public Set getPendencies() {
        return Hibernate.isInitialized(this.pendencies) ? Collections.unmodifiableSet(this.pendencies) : new HashSet<>();
    }
    

    In my case I was giving the error because whenever I was returning a pendencies, as a good practice I converted it to a list that cannot be modified, but how it could or might not be in lazy depending on the method I used to get instance (with or without fetch), I do a test before it was initialized by Hibernate and add the annotation that prevents serializing an empty property and that solved my problem.

提交回复
热议问题