I\'m trying to print ordered list after persisting it and retrieving.
My Entities:
@Entity
public class News {
@Id @GeneratedValue
private Long i
@OrderBy
is applied when sql query is executed. In your case the data is already in memory so sql query is not executed. You can try using @Sort
annotation that apply sorting in memory. Depending on your use case it may not be efficient if your list is big.
@Sort(type = SortType.COMPARATOR, comparator = CommentsComparator.class)
EDIT: @Sort is a hibernate specific annotation. For pure JPA I think the collection (List) can be updated to some sorted collection like SortedSet if possible.
I guess that you are getting your entity from the entity manager and not from db, so you are getting the same object that you created (not sorted object). You should try to refresh caché before the em.find()
method:
em.getTransaction().begin();
em.persist(n1);
em.getTransaction().commit();
// Clear object
em.getEntityManagerFactory().getCache().evict(News.class, n1.getId());
// find
News news = em.find(News.class, n1.getId());
for (int i=0; i<news.getComments().size(); i++){
System.err.println(news.getComments().get(i).getLikes());
}
From Javadoc, the method:
<T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey)
Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.
I empathize the part that maybe is getting you troubles.