JPA: não é possível fazer o OrderBy funcionar
Estou tentando imprimir a lista ordenada após persistir e recuperar.
Minhas entidades:
@Entity
public class News {
@Id @GeneratedValue
private Long id;
private String content;
@OneToMany(cascade = CascadeType.ALL)
@OrderBy("likes DESC")
private List<Comment> comments = new LinkedList<>();
//------------------
}
@Entity
public class Comment {
@Id
@GeneratedValue
private Long id;
private String content;
private int likes;
}
Snippet de método principal:
tx.begin();
{
// persist
News n1 = new News("Super news!!");
Comment c1 = new Comment("comment 1", 1);
Comment c2 = new Comment("comment 2", 200);
Comment c3 = new Comment("comment 3", 10);
n1.addComment(c1);
n1.addComment(c2);
n1.addComment(c3);
em.persist(n1);
// 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());
}
}
tx.commit();
O resultado foi impresso em ordem de declaração (1 -> 200 -> 10) e espero (200 -> 10 -> 1). Alguém pode ajudar com isso?