0

I have to code an Stateless EJB3 that uses callable statements, and builds a XML structure. I'm getting a DataSource Connection from JNDI;

ctx.lookup('DS').getConnection();

my ejb has lots of methods(that build each part of the XML), and i found it is cumbersome to pass the connection as a parameter to every method that i could call.

the thing is:

Should I put the connection as a field in my ejb, open it on @PostConstruct and close it only on @PreRemove? so that it would use the same connection OPEN for the entire lifetime of the bean.

or

Should I use an Interceptor with a try/cacth block that opens the connection and asign it to the bean on every call? Moreover wouldn't this cause concurrency problems? given the connection is a field and is shared by the threads calling the stateless bean methods?

I think I want the same thing we can do with JPA:

@PersistenceContext EntityManager em;

public String businessMethod(String param){
    em.find(...);
    someMethod(param);
}

private void sometMethod(String param){
    em.createQuery...;
}

but with java.sql.Connection

thanks in advance

Victor

1 Answers1

0

To avoid passing connection as parameter to all methods, you can try field-based injection for the data-source.

@Resource(name="defaultDS")
    private javax.sql.DataSource defaultDS;

Then you can have the data-source available in all the methods present in that bean & can get connection from it.

Nayan Wadekar
  • 11,444
  • 4
  • 50
  • 73