此特定环境下的计划: EJB3.0 + JPA + jersey Web Service
第一实体:
@Entity
@Table(name = "student_by_test_yao")
public class StudentTest implements Serializable {
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToOne
@JoinColumn(name = "class_id")
private ClassTest classes;
public StudentTest() {}
}
第二实体:
@Entity
@Table(name = "class_by_test_yao")
public class ClassTest implements Serializable{
@Id
@GeneratedValue
private Integer id;
private String name;
@OneToMany(mappedBy = "classes",cascade = CascadeType.ALL, fetch=FetchType.EAGER)
private List<StudentTest> students;
public ClassTest() {}
}
当我拿到ClassTest的学生名单时。 例外是:
com.fasterxml.jackson.databind.JsonMappingException:
Infinite recursion (StackOverflowError)
如果我更改了获取FetchType.LAZY,则异常为:
org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role:
cn.gomro.mid.core.biz.goods.test.ClassTest.students,
could not initialize proxy - no Session
如何解决我的问题?
答案 0 :(得分:1)
尝试将@JsonIgnore注释添加到其中一个字段以避免循环
答案 1 :(得分:1)
Snippet必须帮助你。
@JsonIgnore
@ManyToOne
@JoinColumn(name = "columnName", referencedColumnName = "id")
private Class class;
答案 2 :(得分:1)
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;
它确实有效。我只是在双向@ManyToOne映射上尝试过。它固定了
com.fasterxml.jackson.databind.JsonMappingException: 无限递归(StackOverflowError)
答案 3 :(得分:0)
对于双向关系,您可以使用这些注释:
父母为@JsonManagedReference,孩子为@JsonBackReference。
此外,此链接可能会有所帮助: Jackson – Bidirectional Relationships