views:

65

answers:

1

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? (I use Hibernate as provider).

+2  A: 

If using extensions is not excluded, you could maybe use @LazyCollection with the EXTRA option:

@OneToMany(fetch = FetchType.LAZY)
@LazyCollection(LazyCollectionOption.EXTRA)
private List<Answer> answers = new ArrayList<Answer>();

This would allow to call answers.size() without loading the collection.

Pascal Thivent