Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining Order in @ElementCollection using Set JPA

Tags:

spring-mvc

jpa

I've been having a lot of issues with JPA and Hibernate. The biggest problem was issuing so many queries it was so slow.

So to counter that I've switched all relationships to Set and been using fetch joins to fetch the object graph in one request.

As a result though, I can't switch to List to get an ordered set of values because the repository throws an exception at startup that Hibernate doesn't handle simultaneous persistent bags as soon as I try to join more than one entity.

So I found a new JPA 2.0 feature called @OrderColumn - but I'm not sure how to apply it to an ElementCollection:

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "variant_option_vals",
        joinColumns = @JoinColumn(name = "variantOption_id")
@OrderColumn(name="sequence")
)

private Set<String> optionValues;

I added the annotation but the sequence column gets added to the base table, not the optionValues table.

Alternatively, is there a way to keep the natural order for the items? i.e keep the order the items were entered, and avoid the simultaneous bags issue?

like image 561
Richard G Avatar asked Oct 18 '25 15:10

Richard G


1 Answers

The @OrderColumn annotation can't be used with Sets, only with Lists.

The OrderColumn documentation documentation says:

Specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list.

For Sets, the only option is to use the @OrderBy annotation using a field of the Entity for ordering, not the insertion order of the Set.

like image 96
David SN Avatar answered Oct 21 '25 14:10

David SN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!