I was reading over the docs regarding Eclipselink’s support for @OrderColumn. It looks like this only applies to List and not Set. The reason I ask is because I have a ManyToMany bi-directional relationship (using a join table) which is a Set and is implemented with a HashSet because the collection can’t have duplicates.
I wanted to order the entries in this set using @OrderColumn, but it appears I can only apply this to List, however using List will break my unique requirement. Is this understanding correct?
If so what is the recommended strategy for this case?
Thanks,
-Noah
This looks similar to the following question:
Why cannot a JPA mapping attribute be a LinkedHashset?
The
Setinterface does not define ordering of elements, so your set needs to be a concrete implementation like aTreeSetorLinkedHashSetimplementation, not just any oldSet. But your JPA provider is generally going to use its own collection implementations with special magic to handle lazy loading.The above answer suggests that there may be some EclipseLink-specific workaround if you are willing to give up lazy loading.
I can think of two options, neither one perfect:
just use a
Listand rely on business logic to enforce uniqueness, with DB UNIQUE constraints as a backstop. Honestly, I end up usingListfor collections almost reflexively, even whenSetwould have been more appropriate; I admit it’s sloppy but has yet to cause any significant problems for me in years of practice.use a
Setand change@ManyToManyto@OneToMany, and make your join table w/order column an actual entity that implementsComparableusing the order column. Then, overload your getter method to do something like