gpt4 book ai didi

java - Spring JPA - 更新 OnetoOne 关系的拥有端时出现 Stackoverflow 异常

转载 作者:行者123 更新时间:2023-12-02 12:23:05 24 4
gpt4 key购买 nike

我在两个对象之间有一个一对一映射。

UserDO.java:

public class UserDO {

@Id
@GeneratedValue
private Long id;

@Column(nullable = false)
@NotNull(message = "Username can not be null!")
private String username;

@Column(nullable = false)
@NotNull(message = "Password can not be null!")
private String password;

@Column(nullable = false)
private Boolean deleted = false;

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private OnlineStatus onlineStatus;

@Column(nullable = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private ZonedDateTime dateCreated = ZonedDateTime.now();

@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private CardDO card;

}

CardDO.java:

public class CardDO {

@Id
@GeneratedValue
@Column(name="id")
private Long id;

@Column(nullable = false)
private Long pan;

@Column(nullable = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate expirationDate;


@Enumerated(EnumType.STRING)
@Column(nullable = false)
private CardType cardType;


@Column(nullable = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private ZonedDateTime dateCreated = ZonedDateTime.now();

@OneToOne(mappedBy="card")
private UserDO user;

}

现在,当我第一次将两者链接起来并将用户对象保存在存储库中时,它工作正常,但每次当我尝试更新用户对象时,它都会抛出 StackOverFlow 异常。

链接两个对象的代码:

userDO.setCard(cardDO);
userRepository.save(userDO);

更新代码:

UserDO userDO = findUser(userId);
userDO.setOnlineStatus(onlineStatus);
userRepository.save(userDO);

可能出了什么问题?

最佳答案

您需要设置关系的所属站点:

public class CardDO {
//skipped

@OneToOne(mappedBy="card", insertable = false, updateable = false)
private UserDO user;
}

@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = card_id)
private CardDO card;

Hibernate脏检查机制发现CardDO已更新,因此想要更新User。然后是,然后是用户等等

关于java - Spring JPA - 更新 OnetoOne 关系的拥有端时出现 Stackoverflow 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45632750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com