To connect mysql, I have a connection object and use the transaction mechanism connection.startTransaction()
, connection.commitTransaction()
, connection.rollbackTransaction()
.
For each startTransaction()
there must always be either a call to commitTransaction()
or rollbackTransaction()
. The absence of such a call or a call to both will break my transaction system.
Therefore, I use them as follows:
boolean i_am_in_a_transaction=true; try { connection.startTransaction(); ... i_am_in_a_transaction=false; connection.commitTransaction(); } finally { if(i_am_in_a_transaction) { connection.rollbackTransaction(); } }
This guarantees the declared order of the call, but it is a lot because I have to write these lines wherever I use transactions.
In C ++, I would use a transaction object that checks its destructor if the commit()
function was called, otherwise rollback()
:
class Transaction { public: Transaction() :am_in_transaction(false) { } ~Transaction() { if(_am_in_transaction) { rollback(); } } void startTransaction() { _am_in_transaction=true; ...start Transaction... } void commit() { _am_in_transaction=false; ...commit Transaction... } void rollback() { _am_in_transaction=false; ...rollback Transaction... } private: bool _am_in_transaction; }
Thus, I have logic implemented in one place and I can use it very simply:
Transaction my_transaction; my_transaction.startTransaction; ... my_transaction.commit();
This code is much simpler than the java code above with a try / finally block.
Is there a way to implement this behavior in Java without allocating logic to the caller and forcing him to implement the try / finally block?
Something like a way to automatically call a function at the output of a region will help me.
source share