The real problem is the collection itself. You should not model your business domain this way. This solution (of collections annotated with @OneToMany
) is only viable for small collections (dozens of objects) and not for large ones (thousands of objects) which may very well be the case with comments. You really have to watch out with them as they can quickly grow out of control. I am using them at the moment only to model the collection of Role
s associated with an Account
, because I know that no account will ever have more than 9 roles in my domain and because the roles an account is in is so very vital to working with the account. For all other m-to-n relations I am using plain old queries.
Instead of adding a collection of comments to your object, add a reference to the object on Comment
and explicitly get the comments you want using a query.
Define a named query on Comment
to get the comments for a certain object (let's use Article
):
@Entity
@NamedQueries(value={
@NamedQuery(name=Comment.FOR_ARTICLE, query=
"SELECT c FROM Comment c WHERE c.article = :article"
)
})
public class Comment {
// ...
@ManyToOne
@JoinColumn(name = "articleId")
private Article article;
}
Then, use that named query i.c.w. Query.setMaxResults and Query.setFirstResult to explicitly control how many results to get and allow for paging etc:
@PersistenceContext
EntityManager em;
Article theArticle = ...;
Query query = em.createNamedQuery(Comment.FOR_ARTICLE, Comment.class);
query.setParameter("article", theArticle);
query.setFirstResult(0);
query.setMaxResults(10);
List<Comment> comments = (List<Comment>) query.getResultList();
To do paging, just setFirstResult
to the first result corresponding with
the page you want to display. E.G. to show results 20 .. 29, you would call
setFirstResult(20)
.