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

时间:2018-10-20 16:36:45

标签: java spring spring-boot jackson jackson2

我在两个实体之间的FetchType.LAZY关系中添加了JsonIncludeOneToMany属性。但是,如果一对多关系集合为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;

}

如果任何公司的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"])]

1 个答案:

答案 0 :(得分:1)

我错过了jackson-datatype-hibernate;配置的对象映射器

public class HibernateAwareObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = -4934273698008915161L;

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

}

解决了它。