简体   繁体   中英

Call method post transaction commit

I have a very peculiar requirement where I have to insert records in 2 tables (audit tables) if insertion in one particular table succeeds. Here I am not talking about @PreInsert in Listener because Listeners are always called in the same transaction. I know that can be done manually by simply calling "save" method after the first save succeeds. BUT I wanted to know is there any other way which I can try using Listener be it JPA/EclipseLink/String-data so that future developers of the application are not forced to insert data in audit table manually.

Basically I am looking for @PostCommit type of functionality. Please help me.

I believe you ultimately do want the callback to run within the boundary of your current transaction, you just want it to run after Hibernate has done its things, just like Hibernate Envers works.

To do this, you basically need to register an event action queue callback like the following:

session.getActionQueue().registerProcess(
  new BeforeTransactionCompletionProcess() {
    @Override
    public void doBeforeTransactionCompletion(SessionImplementor session) {
      // do whatever you want with the session here.
    }
  }
);

If you ultimately must run your code outside the transaction, you could do something similar:

session.getActionQueue().registerProcess(
  new AfterTransactionCompletionProcess() {
    @Override
    public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) {
      // do whatever you want with the session here.
    }
  }
);

That should get you going either way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM