JPA:无法使OrderBy工作

我试图在持久化并检索之后打印有序列表。

我的实体:

@Entity public class News { @Id @GeneratedValue private Long id; private String content; @OneToMany(cascade = CascadeType.ALL) @OrderBy("likes DESC") private List comments = new LinkedList(); //------------------ } @Entity public class Comment { @Id @GeneratedValue private Long id; private String content; private int likes; } 

主要方法片段:

 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(); 

结果按声明顺序打印(1 – > 200 – > 10),我希望(200 – > 10 – > 1)。 有人可以帮忙吗?

我猜你是从实体管理器而不是从db获取你的实体,所以你得到你创建的同一个对象(不是排序对象)。 您应该尝试在em.find()方法之前刷新caché:

 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 

从Javadoc ,方法:

  T find(java.lang.Class entityClass, java.lang.Object primaryKey) 

按主键查找。 搜索指定类和主键的实体。 如果实体实例包含在持久性上下文中,则从那里返回它

我同情那可能让你烦恼的部分。

执行sql查询时应用@OrderBy 。 在您的情况下,数据已经在内存中,因此不执行sql查询。 您可以尝试使用在内存中应用排序的@Sort批注。 根据您的使用情况,如果您的列表很大,可能效率不高。

 @Sort(type = SortType.COMPARATOR, comparator = CommentsComparator.class) 

编辑:@Sort是一个特定于hibernate的注释。 对于纯JPA,我认为如果可能的话,集合(List)可以更新为一些排序集合,如SortedSet。