当杰克逊试图将我的数据解析为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和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,我已经这样做了。
答案 0 :(得分:1)
根据评论,您说您使用的是Jackson 1.9.10
,您可以通过为访问类型添加@JsonProperty
和READ_ONLY
属性来使用WRITE_ONLY
注释的新语法
所以你可以使用:
@JsonProperty(access = Access.WRITE_ONLY)
使用您的字段定义。
有关详细信息,请查看 Only using @JsonIgnore during serialization, but not deserialization 讨论。
注意:强>
对于较旧的版本,您可以在类成员getter上使用@JsonIgnore
,在其setter上使用@JsonProperty
。
答案 1 :(得分:0)
也许您的问题是由错误的映射引起的,您不应该在@JoinColumn
实体中使用@OneToMany
Thing
关系,您需要添加mappedBy = "thing"
作为参数正确指定关系。