Issue
I use JPA Repository with Hibernate as data source in a spring boot application.
My data before:
[{"id":1,"name":"Not Stack"},{"id":2,"name":"Overflow"}]
I do a save operation with this data:
{"id":1,"name":"Stack"}
Then when I do findAll() it retrieved:
[{"id":2,"name":"Overflow"}, {"id":1,"name":"Stack"},]
Is this how it supposed to work? Any idea or workaround about this problem?
Solution
findAll()
returns the data in an unordered manner. The way it sorts these records is up to the RDBMS, and is usually the most convenient way. Relying on the order in this case is not a good idea.
To guarantee that the records are sorted by ID you can create your own method in your repository, for example:
// Full query
@Query("SELECT t FROM Type t ORDER BY t.id")
List<T> findAllOrdered();
// Shorthand relying on method naming
List<T> findAllOrderById();
More information about the method naming can be found at 4.3.2 Query creation in the Spring Data JPA reference.
Or you can use the findAll(org.springframework.data.domain.Sort)
method, for example:
repository.findAll(Sort.by("id"));
Answered By - g00glen00b
Answer Checked By - Clifford M. (JavaFixing Volunteer)