Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

hibernate - JPA EventListener method not called on change to many-to-many collection?

I am using JPA with Hibernate as the implementation in my Spring webapp.

I use EntityListeners for auditing (Spring-data) and other notification purposes. In general it works fine. However, when changes are made to a many-to-many collection/relationship, without any other change to any field of the entities themselves, the @PostUpdate event of the EventListeners are not fired.

To give a concrete example : I have a User and a Role entities, with a many-to-many relationship between them, using an underlying table. If I go to my user management GUI, and add (or remove) roles to a user, without changing anything else, the "postUpdate" event is not triggered, the auditing information is not modified.

There is some logic to it (at a low level) since neither the user or the role tables are updated, only the relationship table is. However the relationship itself is not modeled as an entity class and so it is impossible to apply auditing to it, at least not at the JPA level, so it would make sense to trigger the change event for the entity itself.

Is this a normal JPA behaviour, or is this specific to Hibernate ? Are there any workaround ? What would you do to trigger this event ? Thoughts ?

Note : I found very few mentions of this limitation, and even less solutions : This SO question (without useful answer) and this post on Hibernate's forum also without any answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The JPA spec is very unclear about changes to collections triggering pre/post update callbacks on the entity that owns them. And by unclear, I mean completely silent. In fact, IMO the wording in the spec implies that the callback should not happen since pre/post update is supposed to happen before/after SQL UPDATE statements are sent for that entity.

Now, if the owning entity is versioned Hibernate treats changes to any collections (any attributes really) it owns as forcing a version increment on the owning entity which will trigger the update of the entity which will in turn trigger the post-update callback.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...