Saturday, May 22, 2010

Sorting JPA Collections

Assume that your database you have a "News" table and a "Comment" table. In your Java entities you have mapped the News and the Comment table as two classes. Different users post comments to your News and you need to display these comments and the web page were the News is displayed. So, the first operation to be done is to sort them according to the post date. You don't need to write a query for it. Just take the comment collection of that specific news and use the @OrderBy annotation in order to sort.

@JoinTable(name="NEWSCOMMENT",joinColumns=@JoinColumn(name="NEWSID"),inverseJoinColumns=@JoinColumn(name="COMMENTID"))

@ManyToMany(fetch=FetchType.EAGER)

@OrderBy("POSTDATE ASC")

private List<Comment> commentCollection;

News news = ... //Here you get your news object

List<Comment> comments = news.getCommentCollection(); //By this operation you accomplish the ordering of the comments shown to the news

In @OrderBy("POSTDATE ASC") the POSTDATE is an attribute of the table of Comments.