-1

I dont know why but when i iterate a Map with thymeleaf, The index order is changing... ?

    <form method="POST" action="/deleteValue">
        <tr th:each="weight : ${user.weights}">
            <span th:text="${weightStat.index}">index</span>
            - <span th:text="${#dates.format(new java.util.Date(weight.key))}"></span>
            - <span th:text="${weight.value}">value</span>Kg
            <input type="hidden" name="key" th:value="${weight.key}"/>
            <button type="submit">X</button>
            <br>
        </tr>
    </form>

OUTPUT (Wrong order), H2 DB (Real order)

Yvonnick U
  • 53
  • 7
  • This is a Java issue not a Thymeleaf issue. See [Java Class that implements Map and keeps insertion order](https://stackoverflow.com/questions/683518/java-class-that-implements-map-and-keeps-insertion-order). Or, use an `ArrayList` instead. – andrewJames Jan 11 '21 at 14:39
  • I missed the fact that you are using a `LinkedHashMap` (according to the tags). Can you show us how you are populating it? Also, are you processing the DB data using ORDER BY, to guarantee retrieval order? – andrewJames Jan 11 '21 at 14:52
  • That was an hibernate issue : check my update ;-) – Yvonnick U Jan 12 '21 at 08:26
  • 1
    Glad you solved it. You can write your own answer, instead of updating the question. This will signal to other people that the problem has a solution. You can even accept your own answer if you want to. – andrewJames Jan 12 '21 at 12:35

1 Answers1

1

I found the issue, Hibernate change automatically Linked or Tree Map to classic hashmap... solution : change the getter

public Map<Long, Double> getWeights() { return new TreeMap<>(this.weights); }

Yvonnick U
  • 53
  • 7