Search code examples
springlistforeachsetthymeleaf

Spring JPA - Fix sorting set between 2 refresh


I'm trying to display list-item name. I've got a dvd-media list. Each dvd-media has a countriesList (Set of countries) dvd-media model

I've got a controller sending a List called "dvds". With thymeleaf forEach function, I succeed displaying countries name but thymeleaf change list-items order when I refresh the page.

For example, at the first page launching, it displays: "country1Name", "country2Name", "country3Name". After refreshing (F5), it displays now: "country2Name", "country1Name", "country3Name".

    <div class="row" th:each="dvd : ${dvds}">
<div class=col-3>
     <div th:each="country, iterStat : ${dvd.countries}"
     th:text="${!iterStat.last} ? ${country.name} + ', ': ${country.name}"></div>
</div>

If i add "iterIndex" property, I can see that countryNames doesn't have the same index between every refresh.

Why is there any logic for displaying list items in a for each tag?

I tried to replace Set with TreeSet in Dvd.class and Country.class but this raise a AnnotationException:Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements

Happy new year to everyone!


Solution

  • Set Collection is not an ordered list, so you can either sort this data on the query that retrieve this data or you could sort it in Thymeleaf:

    <div th:each="country, iterStat : ${#lists.sort(dvd.countries)}"