0

When retrieving values from DB hibernate does not keep insertion order in collections of type Set but keeps it in List collections. I've tried to specify LinkedHashSet manually but it does not help.

I have below parent entity

@Entity
@Table(name = "radio")
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class Radio extends AbstractField {

   @OneToMany(cascade = CascadeType.ALL)
   @JoinColumn(name = "radio_id")
   private Set<Choice> choices = new LinkedHashSet<>();
}

And child entity:

@Entity
@Table(name = "choice")
public class ChoiceEntity  {

   @Id
   @GeneratedValue
   @Column(name = "id", nullable = false)
   private UUID id;

   @Column(name = "value")
   private String value;
}

When I am retriving values from the DB, hibernate stores them in choices collection in random order. When I've changed collection type to use List everything works fine.

Is it possible to configure hibernate to keep DB order in the collections of type Set without using any addition order_row.

Aliaksei Stadnik
  • 1,692
  • 3
  • 15
  • 32
  • it's the definition of a Set - it's unordered :) https://stackoverflow.com/questions/1035008/what-is-the-difference-between-set-and-list – sashok_bg Oct 27 '17 at 12:46
  • But LinkedHashSet keeps insertion order, and iteration over LinkedHashSet actually provides correct order. I am wondering is it possible to configure hibernate to use it. – Aliaksei Stadnik Oct 27 '17 at 12:53
  • imo if you need an order, then you should make sure things are properly ordered on your DB side, by using either an ID, a date or some other field and put an ORDER BY in your query – sashok_bg Oct 27 '17 at 12:55
  • @sashok_bg why I could not just rely on DB insertion order? – Aliaksei Stadnik Oct 27 '17 at 13:01
  • 1
    It is the nature of databases and in general of set theory in math. A set is a collection of data with similar properties and order does not matter. Check this question https://dba.stackexchange.com/questions/6051/what-is-the-default-order-of-records-for-a-select-statement-in-mysql – sashok_bg Oct 27 '17 at 13:04
  • 1
    There is also an abstraction on how your database persist the information on disk. There lots of optimisations done by the DB engine like caching indexing and so on and nothing can guarantee that your records are persisted in the same order. As a matter of fact they may not even reside on the same server if you have a distributed database cluster – sashok_bg Oct 27 '17 at 13:07
  • @sashok_bg got it,thanks. – Aliaksei Stadnik Oct 27 '17 at 13:09
  • no problem, hope this helps :) – sashok_bg Oct 27 '17 at 13:10

1 Answers1

0

Use @javax.persistence.OrderBy or @org.hibernate.annotations.OrderBy. The former expects a fragment defined in HQL/JPQL whereas the latter expects a SQL fragment

Steve Ebersole
  • 9,339
  • 2
  • 48
  • 46