Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Method for Database Connection

 
Deepak Mahbubani
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
In our web-site www.goku.co.jp , 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;
try{
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 {
try{
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
author
Ranch Hand
Posts: 3892
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Kyle
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 http://members.aol.com/kgb1001001 for other WebSphere information.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kyle,
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.
-Miftah
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic