What I have is an application that have many events. These events are in chronological order but all I get is a JSON array of eventCodes so the array order is the order in which they were added.
It seems hibernate prefers Set
s over List
s from what I can find on google and SO however using a Set
I need to maintain order of the entries for which I have chosen to use LinkedHashSet
because it maintains insertion order (based on plenty of SO questions).
Which is where my issue is. I have set an OrderBy
on sequence of an applicationEvent which is the index of the JSON array for that object (insertion into the DB seems random so using Id did not work). Looking at the hibernate generated SQL it seems to be getting what I expect. All the event in order of Sequence 1-n.
However when I loop to build a list the order seems to be random not respecting what I perceive as the appropriate insertion order.
Iterator<ApplicationEventDTO> iter = applicationEvents.iterator();
List<ApplicationEventDTO> list = new ArrayList<ApplicationEventDTO>();
while(iter.hasNext()){
list.add((ApplicationEventDTO) iter.next());
}
Application Entity:
@Entity
@Table
public class Application {
//Lots of other stuff
private Set<ApplicationEvent> applicationEvents=new LinkedHashSet<ApplicationEvent>();
@OneToMany (mappedBy = "application", fetch = FetchType.EAGER
, cascade=CascadeType.ALL, orphanRemoval=true)
@NotAudited
@OrderBy("sequence")
public Set<ApplicationEvent> getApplicationEvents() {
return applicationEvents;
}
public void setApplicationEvents(Set<ApplicationEvent> applicationEvents) {
this.applicationEvents = applicationEvents;
}
}
Update
To add a bit more information it was the below articles that lead me to stick with Sets over Lists.
https://vladmihalcea.com/hibernate-facts-favoring-sets-vs-bags/
Hibernate cannot simultaneously fetch multiple bags -- A comment at the end suggest that Sets are preferable over Lists.
The Application Entity is very large and has many relationships. All of which appear to be Sets. When Attempting to change Events to a List I receive: cannot simultaneously fetch multiple bags
which is how I found the SO question.