Hello.
I have a database in which an entity (say, User) has a list of entities (say, List). As a requirement, I must have a denormalized count of the entities on the list:
@Entity
class User {
/* ... */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Friendship> friends;
public int friendsCount;
/* ... */
}
When I add a new element to the list, I must, transactionally, increase the corresponding counter.
I tried to do so using an EntityListener:
class MyBrokenEntityListener {
@PostPersist
public void incrementCounter(Friendship friendship) {
friendship.getUser1().incrementFriendsCount();
}
}
The entity listener is being correctly called, and while debugging I can see that it correctly modifies the entity. However, Hibernate sends no UPDATE query to the database, only the INSERT query (corresponding to the Friendship entity).
I have tried different events on the EntityListener, but it does not seem to work.
What I suppose is happening here is that the entity listener is triggered by an update to the a User. It then identifies all the dirty properties of the user, which consist of the List alone. Therefore it has nothing to do about the User, it has only to insert a Friendship. It then cascades the operation to the Friendship. The entity listener is called, it modifies the user, but at this time Hibernate has already determined that it had not to worry about the user, therefore it does not update the user.
Is this reasoning correct?
If so, how can I properly achieve this?
Thanks, Bruno