Topic
  • No replies
Mauri_Claudio
Mauri_Claudio
4 Posts

Pinned topic How to use DataSources with WebSphere 8.0 (Java Enterprise 6)

‏2011-08-06T10:18:19Z |
Hello everyone,
I just started using websphere 8.0 and I'm running some tests to become familiar with Java Enterprise 6.0, especially with EJB 3.1.
I need advice on how to use the direct injection of data sources. Before WAS 8.0, I used to execute a direct lookup of the datasource.. and since in my projects I have several datasources that may be potentially used
(actual datasource choice depends on user's profile), I was forced to declare for each EJBS in the deployment descriptor all resource refs.

Now with annotation-based configuration, I'm able to write code like this:


@Stateless @LocalBean 

public 

class BaseService 
{   @Resource(name=
"X", lookup=
"jdbc/X") 

protected DataSource X; 
//..... @Resource(name=
"Y", lookup=
"jdbc/Y") 

protected DataSource Y; 
/** * Default constructor. */ 

public BaseService() 
{ 
// TODO Auto-generated constructor stub 
} 

protected getActualConnection(String connName) 
{ Connection conn = 

null; 

try 
{ System.out.println(
" Try to get connection...."); 

if(connName.equals(
"X")) conn = X.getConnection(); 

if(connName.equals(
"Y")) conn = Y.getConnection(); System.out.println(
" Connection ok."); 

return conn; 
} 

catch(Exception e) 
{ System.out.println(
" Error : "+e.getMessage()); 

return 

null; 
} 
}   
}


and using full-supported inheritance, I just let my ejbs extend BaseService to have centralized method to get (internally) a connection and release it after using.

There are a couple of things on which I need advice...

a) I noticed that without the

lookup
properties in Resource annotation, I need to introduce an ejb xml descriptor to declare potential usage of datasource. Otherwise, I get a list of errors like ' Unable to resolve reference..' in my log. It is corrected ? I thought that in Java EE 6, deployment descriptors were totally optional.

b) What do you think about centralizing (of course, with code smarter than that I posted for example) the datasource lookup method ? I'm in doubt if this may considered a good thing or not...

Thank you in advance..