AfterInsertEntityListener after transaction commit

Hi

the documentations says:

AfterInsertEntityListener
onAfterInsert() is called after a record is inserted into database, but before transaction commit. This method does not allow modifications of the current persistence context, however, database modifications can be done using QueryRunner.

After I insert a payment I want to calculate the sum of all the payments already recorded, including the one that I am inserting now. How can this be done with QueryRunner in a listener? Now it only gets the sum for previous payments (already committed) and I have to add the current one in script, but the logic for delete and update listener is not that simple.

Thank you

1 Like

Any Ideas on this issue? I have many situations where I need to perform checks after the entity is saved (the checks need to take into consideration the saved entity) … for now I do not want to use custom logic for 3 situations: insert / update / delete . Do you have any other suggestion?

Kind regards
Geroge

Hi George,

I’m sorry for not replying for a long time.

I think QueryRunner should work in your situation if you use its methods accepting Connection object which is available in the “after” listeners. Then your query will run in the transaction that saved the entity and you should see it in the query results. If it doesn’t work for you, please provide a small sample project demonstrating the issue.

Consider also using “before” listeners - then you can use EntityManager and JPQL queries and still get the same results, because if you execute a query, all modified entities in the current persistence context will be flushed to the database and get selected by the query.

using Connection works, thank you