Java Hibernate上@JsonIgnore的Jsonparsing错误

Java Hibernate上@JsonIgnore的Jsonparsing错误,java,json,hibernate,Java,Json,Hibernate,当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 re

当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
}
在stackoverflow上搜索它会得到以下结果:


链接基本上是说我应该添加@JsonIgnore,我已经这样做了。

也许你的问题是由于映射错误造成的,你不应该在Thing entity中使用@JoinColumn作为@OneToMany关系,您需要添加mappedBy=thing作为参数来正确指定关系。

从您的评论中可以看出您正在使用Jackson 1.9.10,这将允许您通过为访问类型添加只读和只写属性来使用@JsonProperty注释的新语法

因此,您可以使用:

@JsonProperty(access = Access.WRITE_ONLY)
使用您的字段定义

有关更多详细信息,请查看讨论

注:


对于较旧的Cercions,您可以在类成员getter上使用@JsonIgnore,在其setter上使用@JsonProperty。

我猜您应该在Stuff类的getting方法上添加@JsonIgnore。尝试了它并更新了问题。@为什么使用Jackson的哪个版本?1.9.10,这可能会导致问题吗?@为什么。
@JsonProperty(access = Access.WRITE_ONLY)