I have the following entities and get an exception if I try to remove a Task
from the TaskList
via removeTask
method.
@Entity
public class TaskList extends GenericModel {
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@OrderColumn(name="position", nullable=false)
public List<Task> tasks = new ArrayList<>();
// ...
public void removeTask(Task task) {
tasks.remove(task);
}
}
@Entity
public class Task extends Model {
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="task_id")
private List<Reservation> reservations = new ArrayList<>();
@ManyToOne
public TaskList taskList;
// ...
}
@Entity
public class Reservation extends GenericModel {
@Id
private String id = Token.generate(8);
@ManyToOne
private Task task;
// ...
}
The exception is:
"CONSTRAINT_INDEX_F ON PUBLIC.TASKLIST_TASK(TASKS_ID)"
Unique index or primary key violation: "CONSTRAINT_INDEX_F ON PUBLIC.TASKLIST_TASK(TASKS_ID)"; SQL statement:
update TaskList_Task set tasks_id=? where TaskList_id=? and position=? [23001-149]
I'm using JPA 2 with Hibernate 3.6.1. Is something wrong with my mapping or is it a Hibernate bug?
UPDATE
It seems to be a Hibernate problem. Something with the order of delete
and update
statements. The following hack solved the problem (partly):
@Entity
public class TaskList extends GenericModel {
// ....
public void removeTask(Task task) {
tasks.remove(task);
tasks = new ArrayList<>(tasks); // only for Hibernate
task.taskList = null;
}
}
Hibernate - clearing a collection with all-delete-orphan and then adding to it causes ConstraintViolationException lead my in the right direction.
But orphanRemoval=true
doesn't work with my workaround. It leads to the next exception: "A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance". So the problem is not really solved.