I'm having problems deleting the child element of a one-to-many relationship entity. Here's a code snippet:
@Override
@Transactional
public void deleteTask(UUID listId, UUID taskId) {
    TaskList list = repo.findOne(listId);
    System.out.println("Old List: " + list);
    for(Task t : list.getTasks()) {
        if(t.getId().toString().equals(taskId.toString())) {
            System.out.println(list.getTasks().remove(t));
            System.out.println("Task with id " + taskId + " deleted.");
        }
    }
    System.out.println("New List: " + repo.save(list));
}
The Task class is this:
@Entity(name = "task")
public class Task implements Serializable {    
    // Id and 3 fields
    @ManyToOne
    @JoinColumn(name="tasklist_id")
    private TaskList parentList;
    // 3 more fields
    // Constructor
    public Task() {}
    //Getters and Setters
}
and the TaskList class is this:
@Entity(name = "task_list")
public class TaskList implements Serializable {
    // Id and two fields
    @OneToMany(mappedBy="parentList", cascade={CascadeType.ALL})
    private List<Task> tasks;
    // Constructor
    public TaskList() {}
}
The Task entity is the child, and even though the save() function returns the truncated TaskList, I can't get the changes to show in a separate query to the database. The number of tasks remains the same. However, deleting a list through repo.delete(listId) works fine with both the list and its tasks gone.
Here, repo is a repository corresponding to the parent TaskList class. All operations to the child Task class happen through a @OneToMany({cascade=CascadeType.ALL}) relation.
For some reason, searching for all TaskLists using repo.findAll() also returns faulty results.
I'm obviously doing something fundamentally wrong. Please tell me what to do.
You need to add orphanRemoval = true to your mapping:
@OneToMany(mappedBy="parentList", cascade={CascadeType.ALL}, orphanRemoval=true)
list.getTasks().remove(t) just removes entity from the collection, so you need to tell JPA to remove it also from DB. This is done by the orphanRemoval attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With