【发布时间】:2011-07-06 12:55:27
【问题描述】:
我正在尝试学习使用 Hibernate,但可能我不理解 @ManyToOne 和反向关系。我有两个实体Author 和Department。一个作者有一个部门,一个部门有许多作者。
当我删除作者时,部门不会发生任何事情。当我删除部门时,作者表中的 FK 应更新为 NULL 值(不应删除作者)。
我发现nice explanation of inversion 并发现Author 是拥有方,根据this thread,当我删除子(部门)时,FK 应设置为NULL。但它不会发生,因为只删除了 Department 并且 FK 保留在 Author 表中(导致 org.hibernate.ObjectNotFoundException: No row with the given identifier exists)。
当我在Department 实体中将CascadeType.REMOVE 添加到@OneToMany 注释时,所有与部门相关的作者也将被删除。上述两种状态都是不可取的。我只想删除部门并将作者表中的 FK 设置为NULL。该怎么做?
Author 和 Department 带有注释的实体:
@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;
}
提前致谢
【问题讨论】:
标签: java hibernate spring null many-to-one