File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes EJB and other Java EE Technologies and the fly likes Static Method for Database Connection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "Static Method for Database Connection" Watch "Static Method for Database Connection" New topic

Static Method for Database Connection

Deepak Mahbubani
Ranch Hand

Joined: May 12, 2001
Posts: 68
In our web-site , we have used Session beans to fire SQL queries on the database. To establish connection to the database, we have written a class with a static method.
This static method is used by all session beans.
public class DBConna {
public DBConna () {
/* static method to get connection to the database used by all session beans */
public static Connection getConnection()throws SQLException,EJBException{
InitialContext context=null;
context=new InitialContext();
DataSource ds=(javax.sql.DataSource) context.lookup("gokuPool");
return ds.getConnection();
}catch(SQLException se){
System.out.println("Unable to get Connect DataBase ");
throw new SQLException("Unable to Connect DataBase");
catch(NamingException ne){
System.out.println("Unable to get Datascource Connection");
throw new EJBException(ne);
} finally {
if(context != null) context=null;
}catch(Exception ne){
System.out.println("Error Closing Context");
throw new EJBException("Error Closing Context");

My concern is over the use of "static". Since just one copy of the method is created in memory, does it mean only one connection is used to serve all database queries ?
Kyle Brown
Ranch Hand

Joined: Aug 10, 2001
Posts: 3892
No, you'll get a new connection for each method request. That's because you're only using temporary variables in the method. Had you made your connection a static variable you would only have had one, but as it is your design is fine.
P.S. You might consider making the DataSource a static variable by the way. DataSources are threadsafe and you really only need one. Every method invocation would return a new connection though.
Kyle Brown,
Author of Enterprise Java (tm) Programming with IBM Websphere
See my homepage at for other WebSphere information.

Kyle Brown, Author of Persistence in the Enterprise and Enterprise Java Programming with IBM Websphere, 2nd Edition
See my homepage at for other WebSphere information.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
What is your opinion on storing the datasource object as a static variable in the session bean, or making getConnection() a static method of the session bean? Would you consider this good or bad design?
Thanks in advance.
I agree. Here's the link:
subject: Static Method for Database Connection
It's not a secret anymore!