I am trying to setup my hibernate application to persist a new Notification entity everytime an Activity Entity is created – at the moment, everything i have tried the Notification just fails to persist silently (no errors in the logs but sql is never executed).
Can anyone confirm that it is even possible to persist additional entities in the Hibernate pre/postPersist listeners?
I have read in the documentation:
A callback method must not invoke EntityManager or Query methods!
But I have read several other discussion threads that seem to indicate that it is possible.
For reference, the two approaches I have attempted are:
-
@PrePersistmethod – setting a cascade.ALL relationship betweenActivityandNotification, and in the PrePersist method simply creating a newNotificationand linking it to theActivitybeing created in a hope that theNotificationwould be persisted. -
@PostPersistmethod – using@Configurableand a ListenerClass, wiring in a service and creating a newNotificationentity and then explicitly calling the entityManger persist
Can someone confirm what I am trying is possible?
Why do you have to persist
Notificationin@PrePersistor@PostPersistfunction? The following code should persist both entities:UPDATE: you can try creating the link inside the Activity’s constructor like this:
One thing to note is that I think you cannot use
@PostPersist. To be more precise, you must linkNotificationtoActivitybefore persistingActivityin order forcascade={CascadeType.PERSIST}to work.