【发布时间】:2017-08-08 09:00:12
【问题描述】:
当 Jackson 尝试将我的数据解析为 Json 时,我得到了这个异常:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: packagename.Thing.Stuffs, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->packagename.Stuff[“thing"]->packagename.Thing[“stuffs"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: packagename.Thing.Stuffs, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->packagename.Stuff[“thing"]->packagename.Thing[“stuffs"])
我有以下实体(名称已替换为 Stuff and Thing):
东西:
@Entity
@Table(name = "stuff")
@SQLDelete(sql = "UPDATE stuff SET deleted = 1 WHERE id = ?")
@Where(clause = "deleted = 0")
public class Stuff implements Serializable {
private Long id;
private Thing thing;
private String stuffName;
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue
public Long getId() {
return this.id;
}
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, optional = false)
@JoinColumn(name = "thing_id", nullable = false)
public Thing getThing() {
return thing;
}
@Transient
public String getStuffName() {
return stuffName;
}
// Setters and constructor(s) omitted
}
事情:
@Entity
@Table(name = "thing")
public class Thing implements Serializable {
private Long id;
private String name;
private List<Stuff> stuffs;
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "name", unique = false, nullable = false, length = 45)
public String getName() {
return this.name;
}
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "thing_id")
@JsonIgnore
public List<Stuffs> getStuffs() {
return stuffs;
}
// Setters and constructor(s) omitted
}
我一直在用谷歌搜索这种类型的错误。当 json-parser 试图解析由于延迟加载而未加载的对象时,似乎会发生这种情况。延迟加载似乎默认开启。我想避免将所有内容都设置为渴望,所以我改为使用 @JsonIgnore。对我没有任何改变。非常感谢您的帮助,这让我发疯了。
编辑:
在两个类中添加@JsonIgnore 和@Eager 给了我另一个问题。如下所示的异常:
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.doResolveException Handling of [org.springframework.http.converter.HttpMessageNotWritableException] resulted in Exception java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
在 stackoverflow 上搜索给了我这个:Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed)
链接基本上是说我应该添加@JsonIgnore,我已经这样做了。
【问题讨论】:
-
我猜你应该在
Stuff类的getThing方法上添加@JsonIgnore。 -
试过并更新了问题。
-
@why_vincent 你用的是什么版本的 Jackson?
-
1.9.10 ,这可能会导致问题吗?
-
@why_vincent 是的。