I tried to retrieve ordered list of elements from the database. From what I understand, @orderBy annotation should be sufficient.
It is possible to annotate two places:
field representing collection
@OrderBy
@OneToMany(cascade = CascadeType.ALL, mappedBy = Entry.REPORT_PROP)
private List<Entry> elements
getter
@OrderBy
public List<Entry> getElements()
The problem intro
If both field and getter are annotated, the retrieved list is correctly ordered. However, if only field is annotated, the retrieved list is using database natural ordering.
The question
Does annotating only field do anything? And if not, why is it possible to annotate only field?
It shouldn’t matter where you put the annotation. Depending on how you annotate, there should be three cases:
should mean that the list is retrieved without any particular order (your SQL database will probably return them in some ordered form, but according to the standard, it is perfectly legal if it doesn’t).
should retrieve the entries ordered by primary key, and
should retrieve the entries ordered by fieldname in ascending order, corresponding to the following JPQL statement: