Currently what i am doing for transaction management is:
Connection connection = getConnection();
connection.setAutoCommit(false);
updateTableX ( connection, ... );
updateTableY ( connection, ... );
connection.commit();
closeConnection();
I would like to know, if it is possible to avoid closing the connection in my ‘updateTableX’ method. Because if someone accidentally closes the connection then my updateTableY will not be having the connection and it will throw the exception.
Just discipline. In general, methods shouldn’t try to take responsibility for closing things passed into them as parameters – with the exception of situations where you create a new object to wrap an existing one.
The way to avoid closing the connection in
updateTableXis just to make sure you don’t put a call toclose()into the code. This is no different than any other bug really. How do you stopupdateTableXfrom arbitrarily updating a different table, or throwing an exception, or doing anything else it’s not meant to? Code reviews, unit tests, integration tests, manual testing etc…I mean you could write a
Connectionimplementation which wraps another connection and proxies all the methods through exceptclose()but it sounds like a waste of time – if you don’t trust the developers involved not to close the connection, do you trust them to get the rest of the code right?