Interacting with sleep mode during calls

I want to write a history component that tracks changes to a specific type of object and records the history lines based on the difference. Please note that this is not a general audit system, it is specific to one type of object.

I believe that I can connect to the sleep mode event model and listen to the events that tell me when everything has changed, keep track of any changes in instances of the type of objects that interest me, and then create my own code to generate history lines.

I want the history lines to be written in one transaction and ideally use sleep mode (therefore use the same session)

I have some questions / problems

  • What sleep events should I catch, assuming that I want to catch only the changes?
  • How can I participate in the same session / transaction as the session that generates events. I read that there are problems associated with the session inside the event handlers?

Any help was appreciated.

+4
source share
3 answers

There is a general audit solution for hibernation objects called envers , which should do the trick.

However, if this solution is not enough (as your comment suggests), the org.hibernate.events package defines the events used. In this case, I would suggest implementing at least the PostUpdateEventListener interface.

+2
source

The pre-insert and pre-update events seem like a good choice.

Your PrePersistEvent and PreUpdateEvent have a getSession() method that:

Session event source for this event. This is the base session from which this event was created.

Thus, using it, you can create new objects and save them in a single session and transaction.

+1
source

When using these events, make sure that you do not touch the session that caused the events. Get a session and get a factory session and open a new session. It will still be in one transaction, but you will avoid many hibernation issues.

In addition, if you start moving around the object graphs of the object that caused the event, then you may get strange errors, since you changed the state of the collection during the flash. There are Jira tickets open for this "mistake."

+1
source

Source: https://habr.com/ru/post/1301711/


All Articles