JPA:无法使OrderBy工作 [英] JPA: can't make OrderBy work
问题描述
我正在尝试在保留并检索后打印有序列表。
I'm trying to print ordered list after persisting it and retrieving.
我的实体:
@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;
}
主要方法片段:
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)。
有人可以帮忙吗?
The result printed in declaration order (1 -> 200 -> 10) and I expect (200 -> 10 -> 1). Can somebody help with this?
推荐答案
我想你是从实体经理那里得到你的实体而不是从db,因此您获得的是您创建的相同对象(不是已排序的对象)。您应该尝试在 em.find()
方法之前刷新caché:
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());
}
来自 Javadoc ,方法:
<T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey)
按主键查找。搜索指定类的实体和
主键。 如果实体实例包含在持久性
上下文中,则从那里返回。
我同情那些可能让你烦恼的部分。
I empathize the part that maybe is getting you troubles.
这篇关于JPA:无法使OrderBy工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!