I have two entities : News has a list of Comment. I want my comments to be ordered by posted date. So I used the @OrderBy annotation as follow :
@Entity
public class News {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String content;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
@OrderBy("postedDate desc")
private List<Comment> comments;
...
}
@Entity
public class Comment {
@Id
@GeneratedValue
private Long id;
private String nickname;
private String content;
private Integer note;
@Column(name = "posted_date")
@Temporal(TemporalType.TIMESTAMP)
private Date postedDate;
...
public Comment() {
}
public Comment(String nickname, String content, Integer note, String postedDate) {
this.nickname = nickname;
this.content = content;
this.note = note;
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
this.postedDate = df.parse(postedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
...
As you can see, the postedDate is of type Date and @Temporal. I persist a news with some comments. But when I return them, they are not ordered by date. Is there anything wrong with this code ? I wrote a test case to show what it should be doing :
@Test
public void createComment() throws Exception {
News news = new News("Death of Michael Jackson");
news.addComment(new Comment("gonzo", "Third comment", 1, "2009-07-03"));
news.addComment(new Comment("elvis", "First comment", 3, "2009-07-01"));
news.addComment(new Comment("gonzo", "Second comment", 5, "2009-07-02"));
news.addComment(new Comment("elvis", "Fourth comment", 2, "2009-07-06"));
tx.begin();
em.persist(news);
tx.commit();
tx.begin();
news = em.find(News.class, news.getId());
tx.commit();
assertEquals("Death of Michael Jackson", news.getContent());
assertEquals(4, news.getComments().size());
assertEquals("First comment", news.getComments().get(0).getContent());
assertEquals("Second comment", news.getComments().get(1).getContent());
assertEquals("Third comment", news.getComments().get(2).getContent());
assertEquals("Fourth comment", news.getComments().get(3).getContent());
}