where is the best palce to count the lazy load property using JPA

Posted by Ke on Stack Overflow See other posts from Stack Overflow or by Ke
Published on 2010-03-27T13:24:34Z Indexed on 2010/03/27 13:33 UTC
Read the original article Hit count: 201

Filed under:

Let's say we have a "Question" and "Answer" entity,

@Entity

public class Question extends IdEntity {
    @Lob
    private String content;
        @Transient
    private int answerTotal;
        @OneToMany(fetch = FetchType.LAZY)
    private List<Answer> answers = new ArrayList<Answer>();
......

I need to tell how many answers for the question every time Question is queryed. So I need to do count:

String count = "select count(o) from Answer o WHERE o.question=:q";

My question is, where is the best place to do the count? (Because I did a lot of query about Question entity, by date, by tag, by category, by asker, etc. It is obviously not a good solution to add count operation in each query.

My first attempt is to implement a @PostLoad listener, so every time Question entity is loaded, I do count. However, EntityManager cannot be injected in listener. So this way does not work.

Any hint?

© Stack Overflow or respective owner

Related posts about jpa