I’m doing some work on a JSP site that was coded very badly. For every single database call the original programmer opens and closes a database connection. I’m adding in some new database operations and I would like to do things a little bit better( something like hibernate will come later when more of the site can be rebuilt ). I was thinking of creating a single database connection when a session starts ( after logging in ), storing it in the session object and then closing it in session listener end of session handling function when the session closes. Is this a sound strategy? Thoughts?
Share
No. Create a container managed connection pooled data source and get it by JNDI on webapp’s startup.
How to create the data source depends on the container in question. In case of for example Tomcat 6.0, you can read it up here: Tomcat JNDI Resources HOW-TO – JDBC Data Sources. In case of for example Glassfish 3, you can do it in the webbased admin console on http://localhost:4848.
Here’s how you can finally get it from JNDI:
You can call
getConnection()on it. It’s sufficient to get the data source only once during webapp’s startup, for example in a static initializer block of your database connection manager or perhaps in aServletContextListener.The connection should always be acquired and closed in the shortest possible scope. Get it inside the
tryblock where you’re executing the query and close it in thefinallyof the very sametryblock. Do not keep the connection open longer than necessary. The connection pool will take care about keeping them open, so the performance is already greatly improved that way.