0

I have a Stateful bean that is used to make a couple database queries. I open the connection in the first method I call, but I only really want to close the connection after the EJB Client is really done with the Stateful bean. I thought that I could put the logic that closes the database connection in the @PreDestroy method.

This seems to be working, but I'm curious as to the implications. When, specifically, does the EJB session complete? This is container managed transactions, so I would assume that when the EJB client method completes, so does the EJB transaction. When, specifically, does the PreDestroy method get called? Is the transaction still around? Or did it already commit and put itself back into the pool? Thanks!

  • You should probably be using stateless beans if all you're using them for is DB queries. – Matt Ball Feb 19 '13 at 03:29
  • You're right. I wrote a generic bean that opens and closes sessions for each db transaction. I need a different stageful bean so I can keep the session open between method calls. I don't want the client of this stateful db bean to have to remember to close the sessions which is why I'm curious about the lifecycle of the transaction as it relates to the bean. – user1608137 Feb 19 '13 at 05:00

1 Answers1

1

Below are the excerpt from specification, which might clarify the statefull session bean lifecycle.

  • At the end of the lifecycle, the client invokes a method annotated @Remove, and the EJB container calls the method annotated @PreDestroy, if any. The bean’s instance is then ready for garbage collection.

  • it would be wrong to perform database operations within a session bean’s PostConstruct or PreDestroy lifecycle callback interceptor methods and to assume that the operations are part of the client’s transaction. The PostConstruct and PreDestroy methods are not controlled by a transaction attribute because handling rollbacks in these methods would greatly complicate the session instance’s state diagram.

  • PreDestroy methods are invoked in an unspecified transaction and security context.

  • The PrePassivate callback notification signals the intent of the container to passivate the instance. The PostActivate notification signals the instance it has just been reactivated. Because containers automatically maintain the conversational state of a stateful session bean instance when it is passivated, these notifications are not needed for most session beans. Their purpose is to allow stateful session beans to maintain those open resources that need to be closed prior to an instance’s passivation and then reopened during an instance’s activation.

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