I am developing a web application (jsf) and I am using oracle db and web logic.
My question is about the “best” approach to create db connection.
Since I need something simple and fast and I need only few sql’s I prefer not to use any db framework like hibernate ….
so I decided to use the web logic data source which I understand is the best option and it’s working for me.
I created a db connection class I order to establish the connection:
And I am using this connection via the bean class something like this:
I would appreciate to get any suggestions about the code (if it’s the right approach) and how can I improve it.
Yes, using a DataSource which is configured into your application server is almost always the way to go. (Even if you're using an ORM like Hibernate you should still do that.)
As for your code: the main problem with your getConnection() method is that it swallows exceptions and forces its caller to notice that they have happened. First of all, lines 10-12 are unnecessary because the result of "new InitialContext()" can never be null. The "new" operator always creates an object, or else it throws an exception.
But when your code catches an exception, it does nothing but print out a vague message and then returns null. This means that the caller of the method has to check whether it got a Connection, or whether it got null. And if it does get null, what should it do? No, this method shouldn't be catching those exceptions at all. It should be throwing them instead.
The rule is that if you don't know what to do about an exception then you shouldn't catch it. Let the caller deal with it. In this case you should either return a usable Connection or you should throw an exception explaining why you couldn't.
Joined: Sep 09, 2005
Thank you for your remarks
I changed the getConnection to this:
In case there is exception then the caller will create a message with appropriate details.
Is there need also to define getConnection as synchronized ?
I think you should also throw an exception in the remaining place where you're still writing a vague message somewhere. In this case you would have to explicitly throw an exception which you create for this particular situation.