0

I am trying to print the list of posts for an author (id=1) ordered by the published timestamp in descending order. I tried using two approaches shown below:

//Query 1
Criteria topCriteria = session.createCriteria(Author.class)
        .setFetchMode("posts", FetchMode.JOIN)
        .add(Restrictions.idEq(1));
Criteria postsCriteria = topCriteria.createCriteria("posts", "P")
        .addOrder(Order.desc("P.published"));
author = (Author) topCriteria.uniqueResult();
//Print author.getPosts()

//Query 2     
author = (Author) session.createQuery("select A from Author A left join fetch A.posts as P where A.id=1 order by P.published desc").uniqueResult();
//Print author.getPosts()

Entity classes:

//Author.java

@Entity
public class Author {

    @Id
    @GeneratedValue
    private int id;

    private String firstname;

    private String lastname;

    @OneToMany(mappedBy = "author")
    List<Post> posts;

    //Getters and Setters omitted
}

//Post.java

@Entity
public class Post {

    @Id
    @GeneratedValue
    private int id;

    @JoinColumn(name="authorid")
    @ManyToOne
    private Author author;

    private String content;

    @Temporal(TemporalType.TIMESTAMP)
    private Date published;

    //Getters and Setters omitted

}

Author.posts from query 1 is not sorted on published column. Query 2 has posts sorted by published column. Both the approaches seem to generate same SQL query.

What do I need to change in Query 1 to produce the same output as that of Query 2?

Hibernate: 4.3.8.Final

Anvesh
  • 395
  • 1
  • 2
  • 10
  • I Used to create an alias in similar cases, something like this may work: Criteria topCriteria = session.createCriteria(Author.class) .setFetchMode("posts", FetchMode.JOIN) .add(Restrictions.idEq(1)) .createAlias("posts", "P") .addOrder(Order.desc("P.published")); – Pusker György Feb 26 '15 at 13:06
  • I tried using **createAlias** instead of **createCriteria** ("posts", "P"). The results are still not sorted. They have the same order as before i.e sorted on post id. – Anvesh Feb 26 '15 at 13:27
  • Oh I misunderstood the problem, You want the List of Post-s to be sorted, if you want to sort the posts everywhere by published the @OrderBy annotation should work, however I know that this is not exactly what you asked for – Pusker György Feb 26 '15 at 13:53
  • OrderBy hardcodes the sorting order. Can we change the sort order dynamically on the collection? – Anvesh Feb 26 '15 at 14:12
  • I don't know any solution for this, sorry. – Pusker György Feb 26 '15 at 14:26

0 Answers0