2

我正在尝试学习使用 Hibernate,但可能我不理解@ManyToOne和反向关系。我有两个实体AuthorDepartment. 一个作者有一个部门,一个部门有许多作者。

当我删除作者时,部门不会发生任何事情。当我删除部门时,作者表中的 FK 应更新为NULL值(不应删除作者)。

我找到了很好的倒置解释,并发现这Author是一个拥有方,根据这个线程,当我删除子(部门)时,FK 应该设置为NULL. 但它不会发生,因为只删除了 Department 并且 FK 保留在 Author 表中(这导致org.hibernate.ObjectNotFoundException: No row with the given identifier exists)。

当我在实体中添加CascadeType.REMOVE注释@OneToMany时,Department所有与部门相关的作者也会被删除。上述两种状态都是不可取的。我只想删除 Department 并将 Author 表中的 FK 设置为NULL. 怎么做?

AuthorDepartment带有注释的实体:

@Entity
@Table(name = "author")
public class Author implements Serializable {

    @Id
    @Column(name = "idauthor")
    @GeneratedValue
    private Integer idAuthor;

    @DepartmentFormat
    @ManyToOne
    @JoinColumn(name = "department", nullable = true)
    private Department department;
}

@Entity
@Table(name="department")
public class Department implements Serializable {

    @Id
    @Column(name="iddepartment")
    @GeneratedValue
    private Integer iddepartment;

    @OneToMany(mappedBy = "department", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    private Set<Author> authors;
}

提前致谢

4

1 回答 1

2

null当删除某个实体时,没有自动设置所有外键的方法。您必须明确获取部门的所有作者,将他们的部门设置为空,然后删除部门。

您还可以使用批量更新查询来执行此操作:

update Author a set a.department = null where a.department = :department

(因此只有一个查询而不是 n + 1),但请注意版本字段不会更新,不会有任何乐观锁定检查,并且会话的已加载部门不会如果这样做会受到影响(在内存中)。

Note that you shouldn't have an ObjectNotFoundException when you're deleting an entity referenced by another one. Instead, you should enable a foreign key constraint in the database so that the removal of the department fails if there is still an author referencing it. That way, your data stays in a coherent state.

于 2011-07-06T13:12:26.287 回答