Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate does wrong insertion order for child entities with composite keys

I have a table that relies on insertion order (bad legacy design that I cannot change) and is having transient entities being inserted in the wrong order. The table in question is called 'Mean' which is a child entity of 'Belief'. When session.save(belief); is called, the action is cascaded to the child mean entities which is stored as a list in the belief class. the Mean entities are stored in the appropriate order in the belief.getMeans() List, but once persisted to the database, they are inserted in order of their composite key. so for example, if there are 3 Mean entities to be inserted with the following order and composite keys:

[1, 1], [1, 3], [1, 2]

They will be inserted ordered by the composite keys like so:

[1, 1], [1, 2], [1, 3]

Any idea as to what might be causing this? I thought Hibernate was supposed to insert based on the order they appear in the List? I even tried running session.save() on each Mean entity individually to see if that would make a difference, but it didn't.

I appreciate your help!

EDIT: So what I ended up doing was adding a new column to the Mean table called col_index which holds the column index of the Mean in the resulting matrix. I used javax.persistence.OrderBy annotation with the new col_index column so the List of Mean entities comes back in the appropriate order. Although, this still does not fix the insertion order problem, and I would still like to have an answer for that. However for now, this solution will have to suffice.

like image 275
Jon McPherson Avatar asked May 12 '15 04:05

Jon McPherson


1 Answers

I think you should use @OrderColumn and not @OrderBy.

The @OrderBy annotation is used when fetching Collection elements but the order is not maintained by Hibernate.

The @OrderColumn allows Hibernate to persist the element Collection index into the designated order column, which is then used when fetching the collection.

like image 184
Vlad Mihalcea Avatar answered Oct 10 '22 13:10

Vlad Mihalcea