khadar valli wrote:Hi Mig,
In General, We will use the method "class.forname()" for JDBC connections.
No No No No No!
Servlets implement web applications. Web applications are not continuously-running programs, they're bits of code that run off of threads assigned on a very short-term basis. They
Must not attempt to hold database Connections between requests, but instead are
required to obtain and release them entirely within a single request and repeat as needed on subsequent requests. If you attempt to hold a Connection between requests, at best you could end up starving the database server and/or local machine for resources and at worst, the
JEE server might attempt to serialize the Connection. And Connections are not serializable, which means that they can be damaged if that is done. In fact, you could potentially crash the whole server. Pool Connections are
much more efficient than "brute-force" connections. They don't require all the extra OS and network overhead to open.
Use a Connection Pool instead. Obtain your Connections from the pool and release them back to the pool (close them) as soon as possible in order to make most efficient use of the finite set of Connections in the pool.
Connection pools are not appserver-specific. They are defined as part of the core implementation, so although the external implementation details may vary between various pool plugins and appservers, the consuming web application doesn't see those details and is invariant. The same code that works in Tomcat will work in WebSphere and in
Wildfly.
You use JNDI to locate the pool you need (an app can have multiple pools if multiple databases are being connected to). Looking up the named connection pool will return a reference to an implementation of javax.sql.DataSource. Invoke the "getConnection()" method on this DataSource to obtain a connection from the pool - and, repeating - close that Connection as soon as you can.
Some J2EE persistence facilities may use alternative mechanisms to interface with their connection pools. For example, JPA-compliant ORMs use EntityManagers. These are usually built on top of a standard connection pool, however.