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