JPA: can't make OrderBy work

后端 未结 2 634
名媛妹妹
名媛妹妹 2021-01-21 11:24

I\'m trying to print ordered list after persisting it and retrieving.

My Entities:

@Entity
public class News {
    @Id @GeneratedValue
    private Long i         


        
相关标签:
2条回答
  • 2021-01-21 12:03

    @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.

    0 讨论(0)
  • 2021-01-21 12:05

    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.

    0 讨论(0)
提交回复
热议问题