Search code examples
javahibernatejpahibernate-mappingspring-data-jpa

Best way to implement an "reorderable" Entity


I have a list of entities shown to the user more or less as a list. Now the user may not only add or delete entities but also reorder the existing ones (with the typical "go up", "go down", "go to the top", "go to the bottom" operations).

But what is the best way to implement this behavior? Of course I can code all the needed operations "manually" in the service layer, but this functionality seems to be a common requirement, so maybe there is already some kind of standard solution?


Solution

  • The most suitable bidirectional collection, is an ordered List:

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent", orphanRemoval = true)
    @OrderColumn("order_id")
    private List<Child> children = new ArrayList<>();
    

    The order_id column will be used to sort elements upon retrieval and when you change the element order, Hibernate will issue the appropriate updates to set the order_id column based on the current element index.