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

标签 hibernate jpa-2.0 cascade one-to-one

我正在使用 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/

相关文章:

java - Spring/Hibernate 同一个实体不同的数据库结构

sql - 使用 JPA 2 在权限模型中存储用于按位比较的整数

java - Hibernate,自动持久化依赖对象

mysql - 获得 "foreign key constraint fails"即使我有 "on delete cascade"

java - J2EE Struts、Spring 和 Hibernate 框架问题

java - 为什么我无法检索刚刚保留的实体?

Hibernate:如何注释 Collection<Object> 以允许搜索

java - 在 java.net.URL 类型对象上执行条件查询的可能性和限制

SQL Server - 使用递归外键进行级联 DELETE

MySQL:尝试获取锁时发现死锁