gpt4 book ai didi

hibernate - 使用@OneToOne注释从表中删除

转载 作者:行者123 更新时间:2023-12-02 22:42:26 25 4
gpt4 key购买 nike

我正在使用 JPA2 和 Hibernate 实现。

我有这样的简单映射:

@Entity 
class Topic {

@Id
@GeneratedValue(strategy = IDENTITY)

int id;

@OneToOne(cascade = ALL)
@JoinColumn(name = "id_poll")
private Poll poll;

}

@Entity
class Poll {
@Id
@GeneratedValue(strategy = IDENTITY)
int id;
}

现在,当我删除主题中的 Poll 对象时,我收到错误。

java.sql.SQLException: Integrity constraint violation FKCC42D924982D3F4B table: TOPICS in statement [delete from polls where id=?]

据我所知,这是因为如果轮询记录在另一个表中有引用,我无法删除它。我怎么解决这个问题?我是否必须在主题表中手动设置 poll = null 还是有更好的解决方案?

最佳答案

这是预期的行为:

A common problem with bi-directional relationships is the application updates one side of the relationship, but the other side does not get updated, and becomes out of sync. In JPA, as in Java in general it is the responsibility of the application, or the object model to maintain relationships.

来源:Object corruption, one side of the relationship is not updated after updating the other side

处理此问题的正确位置是在 @PreRemove 回调中:

@Entity 
class Poll {

...

@PreRemove
private void preRemove() {
Poll poll = topic.getPoll();
topic.setPoll( null );
}
}

另请参阅:Have JPA/Hibernate to replicate the “ON DELETE SET NULL” functionality

关于hibernate - 使用@OneToOne注释从表中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4580960/

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