In Play framework how do I list only a certain number of object from database instead of all.
Suppose that I have this Post class that has a @OneToMany relation with Comments just like this
public class Post extends Model {
@ManyToOne
public User user;
public String name;
public String description;
public String image;
public Date created_date;
@OneToMany(mappedBy="post", cascade=CascadeType.ALL)
public List<Comment> comments;
....
}
How do I only list top 5 comments for each post at the template? I’ve done this, but it shows all comments
#{list items:post.comments, as:'comment'}
<p>${comment.comment}</p>
#{/list}
Thanks
You can just use standard Java to get the sub list
The above will return an array index out of bounds if there are less than 5 comments though, so you can either put some more logic in the template (as below), or you could create a getter method in your
Postmodel that gets the top5 comments, and just call this instead (which is probably the cleaner and preferred option.The extra logic in the template would look like
If you agree that this is too much logic in your view, and want to encapsulate it in your Model, you could do the following.
The extra logic in your view may look like
And then your controller would be