Hi all, I have a stateless session bean with many methods. I've an external class for connecting to a db datasource. Each method in session bean calls the method in the external class to open connection. At the the end of session bean's method the connection is closed. So there are many open/close connection operations (one for each method). Is it correct to declare in session bean a private variable to hold the connection and then open it in ejbCreate() and close it in ejbRemove()? How can I avoid doing an open/close operation for each method? Thanks in advance and for any suggestion
- Posted by: Davide N
- Posted on: May 08 2007 19:37 EDT
- Re: Open/close Db connection in stateless session bean by D S on May 09 2007 08:14 EDT
Is it correct to declare in session bean a private variable to hold the connection and then open it in ejbCreate() and close it in ejbRemove()?No. The best way to do this is to use a connection pool. This gives you a pool of connections which are managed independently of your session bean and that are already open when you need them. So, in your session bean all you would do is to request a connection from the pool whenever you need one. You don't need to try to hold on to the connection between calls to the session bean. Once you are finished with it, it gets returned to the pool. Depending on which application server you are using, there are different ways to manage this, but for what you want, connection pooling is the answer.