Why is it that Stateful session beans are able to call getUserTransaction (on their SessionContext) in the ejbCreate/ejbRemove methods i.e. when not in a transaction context but Stateless beans are not able to do the same thing?
getUserTransaction() is invoked before a transaction starts. This method only makes sense in the right context. By context, I mean client context. For a stateful session bean, ejbCreate() is only invoked in response to a client's create() method, so this is the right context. The fact that ejbCreate() is called with an unspecified transaction context is irrelevant, you can invoke getUserTransaction() from ejbCreate(). Remember, the ejbCreate() and ejbRemove() methods of a stateful session bean are like business methods.
But for a stateless session bean, ejbCreate() is invoked when the container needs to create instances in the pool, it is nothing to do with the client (which might not even exist at this time). This is why getUserTransaction() can only be called from a business method of a stateless session bean, ie after ejbCreate().
thanks for you answer, Roger. You are saying that a client context is a necessary prerequisite for a successful call to getUserTransaction(). Sorry to press you, but can you think of any reason why this is so?
Let's look at it this way. Which methods might you want to run in a transaction? It's business methods, right? So, it makes sense for the ejbCreate() method of a stateful session bean to get a UserTransaction object and start a transaction (because it is kind of a business method) but it makes no sense for a stateless session bean.
I'm not claiming to know the answer as neither the EJB spec nor the Head First EJB book explains this, but it's my best shot at fuguring it out.
The getUserTransaction() method can always be called from the ejbCreate() and the ejbRemove() methods of a stateful or a stateless session bean. But for a stateless session bean, you can only do something with that UserTransaction object, call begin(), from a business method. Contrast this with a stateful session bean where you can do something with that UserTransaction object from ejbCreate() and the ejbRemove().
The reason is the same in both cases, you need to be in a client context to call the UserTransaction methods.
SCJP 1.4, SCWCD 1.3, SCBCD 1.3
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop