Search code examples
javajdbcliferayportlet

Closing jdbc resources in liferay portlet


For ResultSets its easy - im closing them just after i read them. Problem is with Connection and PreparedStatements. Im not sure when its best to close those resources.

For defensive approach its seems good to close them after each complex action on database, but that means that i will have to open connection and compile prepared statements every time user call any portlet action (for example every page reaload, or ajax request that calls MVCPortlet#serveResource).

Is there any better way to manage jdbc connection ? When its best to close all those resources ?

Maybe its not a big deal to set up database connection and statements every time any portlet action is called ?


Solution

  • Most straight-forward way is likely this utility class http://docs.liferay.com/portal/6.0/javadocs/com/liferay/portal/kernel/dao/jdbc/DataAccess.html

    You can pass all the opened resources to DataAccess.cleanUp() in a finally statement, in practice it just does null checking and exception handling for you.

    If there's a PreparedStatement that gets called a lot perhaps it could be kept around between requests but it's the sort of late stage optimization to think about when there's nothing else left to do. The overhead is minimal.