Spring Architecture循环引用和stackoverflow

时间:2017-03-28 18:30:40

标签: java spring circular-reference

我有一个关于如何避免循环引用和堆栈溢出的问题。

我有一个User对象和另一个News对象(带有User变量)。我需要一个Comments对象(已经有一个News变量),但我还需要它有一个对创建了Comment的User的引用。

如果我在Comment对象中创建一个User变量,我会有循环引用和stackoverflows,所以我认为我应该只在我的Comment对象中包含一个像userid这样的变量。

所以可能是我正确的思考或者我做错了以获得stackoverflow错误。你会做什么以及为什么?如果你能提供帮助,那就太好了。感谢。

这是用户......

@Entity
@Table(name = "users")
@PasswordMatch(message = "{register.repeatpassword.mismatch}")
public class SiteUser {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true)
@Email(message = "{register.email.invalid}")
@NotBlank(message = "{register.email.invalid}")
private String email;

@Transient
@Size(min = 5, max = 15, message = "{register.password.size}")
private String plainPassword;

@Column(name = "password", length = 60)
private String password;

@Column(name = "enabled")
private Boolean enabled = false;

@NotNull
@Column(name = "firstname", length = 20)
@Size(min = 2, max = 20, message = "{register.firstname.size}")
private String firstname;

@NotNull
@Column(name = "surname", length = 25)
@Size(min = 2, max = 25, message = "{register.surname.size}")
private String surname;

@Transient
private String repeatPassword;

@Column(name = "role", length = 20)
private String role;

public SiteUser() {

}

状态更新(您可以将其称为新闻或文章)。它有一个网站用户,就是创建该文章的用户。

@Entity
@Table(name = "status_update")
public class StatusUpdate {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Size(min=5, max=255, message="{addstatus.title.size}")
@Column(name = "title")
private String title;

@Size(min=5, max=5000, message="{addstatus.text.size}")
@Column(name = "text")
private String text;

@Column(name = "added")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss")
private Date added;

@OneToOne(targetEntity = SiteUser.class)
@JoinColumn(name="user_id")
private SiteUser siteUser;

@PrePersist
protected void onCreate() {
    if (added == null) {
        added = new Date();
    }
}

public StatusUpdate() {

}

可以由任何注册用户完成的评论,对吗?正如您将注意到,Comment没有User对象以避免循环引用。这就是问题所在。如果自动装配用户

,如何避免循环引用
@Entity
@Table(name = "comments")
public class Comment {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "statusupdateid")
private StatusUpdate statusUpdate;

@Column(name = "commenttext")
private String commenttext;

@Column(name = "commentdate")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy/MM/dd hh:mm:ss")
private Date commentdate;

@Column(name = "userid")
private Long userid;


public Comment() {
}

0 个答案:

没有答案