Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HibernateException: Found two representations of same collection

If I save an object containing the following list

@OneToMany(cascade=CascadeType.ALL, mappedBy="taskList")
@OrderColumn(name="position", nullable=false)
public List<Task> tasks = new ArrayList<Task>();

I get the exception

org.hibernate.HibernateException: Found two representations of same collection

The code in the Play! controller looks like this:

TaskList taskList = taskList.findById(taskListId);
taskList.add(position, task);
taskList.save();

If I insert taskList.refresh() before this block it works, but the position information is lost (which leads to other errors).

Is this a Hibernate bug or is something wrong with my code?

like image 872
deamon Avatar asked Nov 29 '11 22:11

deamon


3 Answers

The same error occurs when you try to modify an associated collection of an object. e.g.:

    MyObject myObject = myObjectService.get(id);
    List<Task> newTasks = //populate new list of Task here
    myObject.setTasks(newTasks);
    myObjectService.saveOrUpdateObject(myObject); // or merge(myObject)      

In such a case, it can be resolved by:

    MyObject myObject = myObjectService.get(id);
    List<Task> newTasks = //populate new list of Task here
    myObject.setTasks(new List<Task>); // or myObject.getTasks().clear();
    myObject.getTasks().addAll(newTasks);
    myObjectService.merge(myObject); 
like image 154
Bhanuka Withana Avatar answered Oct 23 '22 00:10

Bhanuka Withana


The problem was, that Hibernate does not support the combination of @OneToMany(mappedBy=...) and @OrderColumn. Without mappedBy Hibernate uses a join table and everything works as expected. See explanation.

like image 36
deamon Avatar answered Oct 23 '22 00:10

deamon


I could resolve the issue by changing the association to lazy and removing the cascade.

@OneToMany(mappedBy="taskList", fetch = FetchType.LAZY)
@OrderColumn(name="position", nullable=false)
public List<Task> tasks = new ArrayList<Task>();
like image 29
Gat Avatar answered Oct 22 '22 23:10

Gat