Combine Set with @OrderColumn

Viewed 217

A general suggestion with m-n relations is to use Set instead of List because it offers better performance for certain operations.

I'm trying to combine this with the annotation @OrderColumn(name = "position"). I use this so I don't need a "join table class". I want Hibernate to set the position value according to the position of the element in the set. Therefore I use a LinkedHashSet.

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinTable(name = "bundle_group_to_bundle", joinColumns = @JoinColumn(name = "fk_bundle_group"), inverseJoinColumns = @JoinColumn(name = "fk_bundle"))
@OrderColumn(name = "position", nullable = false)
private Set<Bundle> bundles = new LinkedHashSet<>();

I can't get this to work. Hibernate ignores the position attribute completely when reading or writing entities. As soon as I replace this with List it works fine.

Does Hibernate support @OrderColumn with Set?

Note: I tried using SortedSet instead of Set but that requires either @Sort (deprecated) or @OrderBy (cannot be used with @OrderColumn) which I can't use in my case.

1 Answers

This is not as much as a Hibernate issue than a Java issue. The Set interface doesn't guarantee any order (Set Javadoc). So in Java, you can't use a plain Set if you want any kind of sorting or order.

Plus, Hibernate creates his mapping from fields' definition, even if LinkedHashSet keeps inserting order, the framework will use the Set to do his job. And any entity loaded through hibernate will have a custom implementation of Set used, a PersistentSet.

On the other hand, List and SortedSet interfaces preserve order and allow sorting.

Indeed, Set generally perform better than List on some operation. But if you can't use SortedSet, you have limited choices.

Related