Reputation: 4538
I would like to use @TransactionalEventListener
to complete a unit of work. In other word, I want to register a transaction callback, which is triggered before the transaction is committed. What I have in mind is a Repository class, which keeps track of the changes done to an aggregate root and all dependant entities. When the transaction is about to be committed it writes the entire set of changes to the DB, as follows.
@Component
@Transactional
class FlightRepository implements Repository{
Flight findById(int id){
// return Flight and start tracking changes
}
void add(Flight f){
// add to list of flights to be created before transaction commit
}
void remove(Flight f){
// add to list of flights to be deleted before transaction commit
}
@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
public void saveChanges(){
// write all changes to db (adds/removes/updates)
}
}
What I need to confirm is whether it is OK to still perform CRUD operations in a TransactionPhase.BEFORE_COMMIT
callback?
Edit: Changed saveChanges()
access modifier from private
to public
as noted in comment
Upvotes: 0
Views: 751
Reputation: 90507
Yes. It is OK. What you do in the BEFORE_COMMIT
callback will be at the same transaction of the unit of work.
By the way, in order for @TransactionalEventListener
to work , you should change its method access modifiers to non private.
Upvotes: 1