JsonInclude не может предотвратить исключение сопоставления для ленивой инициализации отношения NULL OneToMany

Я добавил свойства FetchType.LAZY и JsonInclude к связи OneToMany между двумя объектами. Тем не менее, я по-прежнему получаю исключения сопоставления при извлечении объекта-владельца, если коллекция отношений «один ко многим» имеет значение 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"])]


person Anadi Misra    schedule 20.10.2018    source источник


Ответы (1)


Мне не хватало jackson-datatype-hibernate; настроенный объектный картограф

public class HibernateAwareObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = -4934273698008915161L;

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

}

это решило это.

person Anadi Misra    schedule 23.10.2018