During a code review I found the following code snippet:
try (
Connection con = new SqlSessionFactoryBuilder()
.build(configuration)
.buildFactory()
.openSession()
.getConnection()
){
// do stuff here with 'con' and not close anything
}
Session, Connection, SqlSessionFactory are iBatis implementations, but the questions is interested in any 'stacked' implementation of the Closable interface.
I am assuming 'try with resources' closes the resource, that is instantiated - con in this case. Normally you'd close session and connection each individually. If using the above code the close() method will just be called on con object, so session is not explicitly called and will rely on the garbage collection?
Will the code be any better using:
try (
Session session = new SqlSessionFactoryBuilder()
.build(configuration)
.buildFactory()
.openSession();
Connection con = session.getConnection();
){
// do stuff here with 'con' and not close anything
}
The latter approach seems cleaner in my eyes as it should call close() correctly. Or is my interpretation wrong and just boilerplate code?
try
syntax is allowed for precisely this reason, after all. – Green Cloak Guy