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();
}
}