Search code examples
javaspringspring-bootjacksonjackson2

JsonInclude fails to prevent mapping exception for lazy initialised NULL OneToMany relationship


I have added FetchType.LAZY and JsonInclude properties to a OneToMany relation ship between two entities. However, I still get mapping exceptions while fetch the owning entity if the one to many relation collection is null.

@Entity
@Getter
@Setter
@NoArgsConstructor
@JsonInclude(value = Include.NON_NULL)
public class Company extends AuditModel implements Serializable {

    private static final long serialVersionUID = 4627788171283297107L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Version
    private Integer version;

    @Column(nullable = false, length = 25)
    private String name;

    @Column(nullable = false, length = 10)
    private String pan;

    @Column(nullable = false, length = 21)
    private String cin;

    private String vatTin;

    @Column(nullable = false, length = 10)
    private String tan;

    private Address address;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "Company_Branches", joinColumns = @JoinColumn(name = "company_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "branch_id", referencedColumnName = "id"))
    private List<Branch> branches;

}

If Branches is null for any Company I get this

2018-10-20 21:59:23.733 WARN 70144 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: com.xxx.xxx.entity.Company.branches, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.xxx.xxx.entity.Company.branches, could not initialize proxy - no Session (through reference chain: java.util.Collections$UnmodifiableRandomAccessList[0]->com.xxx.xxx.entity.Company["branches"])]


Solution

  • I was missing jackson-datatype-hibernate; configured Object Mapper

    public class HibernateAwareObjectMapper extends ObjectMapper {
    
        private static final long serialVersionUID = -4934273698008915161L;
    
        public HibernateAwareObjectMapper() {
            registerModule(new Hibernate5Module());
        }
    
    }
    

    that solved it.