Question

I have an entity "post", which has a set of many "comments". Now I don't want to count the size of this set everytime I want to show the number of comments and therefore I want to create an integer field and store the number of comments here. If a comment is posted, I want to increase it, if a comment is deleted I want to decrease it.

Is there any "out of the box"-approach provided by hibernate for that? Or do I need to implement that by hand? (I think its not that trivial because I have to consider concurrency problems etc.)

Was it helpful?

Solution

I don't there is out-of-the-box solution for hibernate to map size of collection to a field. There are usually 2 ways that you can choose, one being more out-of-the-box, while the other one being more safe

1) Consider using pre-persist and pre-update

Something like this

public Foo {
  @OneToMany
  private List<Bar> bars;

  @Column
  private int barSize;

  @PrePersist
  @PreUpdate
  public void updateBarSize() {
    this.barSize = (bars==null ? 0 : bar.size());
  }
}

2) Instead of allow direct manipulation of the collection in your entity, provide addChild(), removeChild() for collection manipulation, and return a immutable clone of collection when getChild(). By doing so, you can safely keep track of the size and update the integer value whenver addChild()/removeChild() is called.

For example

public Foo {
  @OneToMany
  private List<Bar> bars;

  @Column
  private int barSize;

  public List<Bar> getBars() {
    return Collections.unmodifiableList(bars);
  }

  public synchronized void addBar(Bar bar) {
    this.bars.add(bar);
    this.barSize = bars.size();
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top