I'm working on a java web application using Struts 2. Currently, on each page load, I establish a new db connection, and then close this db connection at the end of the request, just before rendering the resulting HTML. So, each request gets its own db connection.
I want to have a bunch of static methods within my model classes, e.g things like User.exists( id )
which would return true if the given user id existed, or false if it didn't. Or other utility methods like User.getEmail(id)
or User.disable(id)
.
My question is, is there a convenient way to share the db connection with these static methods? Having to pass on the connection as a 2nd argument to all these methods, e.g User.exists(id, db)
would be ugly, and not too convenient.
What about if I obtain a new db connection in each of these utility methods, and close it before returning the result? Would it have any impact on the perfomance? I could need to call these methods 20-30 times within a request some times (such as when validating user input).