[英]Getting data from a Bidirectional One to Many Relationship in Hibernate/Spring Data
As following the instructions or tutorials posted online on how to create a bidirectional One To Many relationships in Hibernate, I was able to create two entity classes: 按照网上发布的有关如何在Hibernate中创建双向“一对多”关系的说明或教程,我能够创建两个实体类:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "user_name",nullable = false)
private String userName;
@Column(name="password",nullable = false)
private String password;
@OneToMany (mappedBy = "user",cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<BlogPost> blogPostSet;
//getters and setters
}
@Entity
@Table(name = "blog_post")
public class BlogPost {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String content;
@ManyToOne
@JoinColumn(name ="user_id")
private User user;
//getters and setters
}
I was able to insert data on these two entities, but the problem occurs when I try to fetch data a recursion happens and results to a stackoverflow error, please see the attached screenshot. 我能够在这两个实体上插入数据,但是当我尝试获取数据递归时会发生问题,并导致stackoverflow错误,请参阅所附的屏幕截图。 What would be the proper way to fetch data on this hibernate relationship?
在这种休眠关系中获取数据的正确方法是什么?
Mapping seems to be fine, probably you have overridden toString() method in both of the entities printing each others relationship references like 映射似乎很好,可能您在两个相互打印关系引用的实体中都重写了toString()方法
class Employee{
public String toString(){
return "blogPostSet "+blogPostSet;
}
class BlogPost{
public String toString(){
return "employee "+employee;
}
Hence calling each others toString() to cause a stackoverflow error. 因此,互相调用toString()会导致stackoverflow错误。
You have to change your toString()
method, of both classes so that it doesn't get recursive. 您必须更改两个类的
toString()
方法,以免递归。 By changing that you can yourself print the things you want so that it doesn't go into recursion. 通过更改,您可以自己打印所需的东西,这样就不会递归。
由于两个实体的ID均为字段名称,因此您必须指定@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property =“ id”),它将解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.