I'm trying to learn to work with Hibernate but probably i don't understand @ManyToOne
and inverse relations. I have two entities Author
and Department
. One Author has one Department, One Department has Many Authors.
When I remove Author, nothing should happen with Department. When I remove Department, FK in Author's table should be updated to NULL
value (Author should NOT be removed).
I've found nice explanation of inversion and figured out that Author
is an owning side and according to this thread when I remove child (Department) the FK should be set to NULL
. But it doesn't happen because only Department is removed and FK remains in Author table (which leads to org.hibernate.ObjectNotFoundException: No row with the given identifier exists
).
When I add CascadeType.REMOVE
to @OneToMany
annotation in Department
entity then all Authors tied to Department are also removed. Neither of aforementioned states are desirable. I just want to remove Department and set FK in Author table to NULL
. How to do that?
Author
and Department
entities with annotations:
@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;
}
Thanks in advance