gpt4 book ai didi

java - JPA:无法使 OrderBy 工作

转载 作者:行者123 更新时间:2023-11-30 06:59:20 25 4
gpt4 key购买 nike

我正在尝试在持久化和检索后打印有序列表。

我的实体:

@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)。有人可以帮忙吗?

最佳答案

我猜你是从实体管理器而不是数据库中获取实体的,所以你得到的是你创建的相同对象(不是排序对象)。您应该尝试在 em.find() 方法之前刷新缓存:

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)

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.

我理解可能给您带来麻烦的部分。

关于java - JPA:无法使 OrderBy 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31644361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com