JsonInclude 无法防止延迟初始化 NULL OneToMany 关系的映射异常

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

我已将 FetchType.LAZYJsonInclude 属性添加到两个实体之间的 OneToMany 关系中。但是,如果一对多关系集合为空,我在获取拥有实体时仍然会遇到映射异常。

@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;

}

如果任何公司的 Branches 为空,我会得到这个

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"])]

我缺少 jackson-datatype-hibernate;配置的对象映射器

public class HibernateAwareObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = -4934273698008915161L;

    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate5Module());
    }

}

解决了。