This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Only enterprise beans with bean-managed transactions are allowed to to use the UserTransaction interface. As entity beans must always use container-managed transactions, only session beans or message-driven beans with bean-managed transactions are allowed to invoke this method.
Well, let's try to address the "Why" of this question. Entity bean interfaces represent individual accesses to attributes, right? So in what context would it use a user transaction? If you tried to use a user transaction in an accessor-type method then that means that EVERY attribute access would have to be its own transaction. That would be horribly, terribly inefficient -- if you had a simple Address EJB then getting all it's attributes would amount to four or five separate transactions!
That's why transaction control has to occur outside the Entity bean, in either the container or in a controlling Session bean -- to create a transaction that has a more meaningful scope.
The actual reason is little bit more subtle and relies upon the way the container should mange the transactions. As per EJB specs entity beans follow a load-and-store cycle for each transaction. This means that the container calls ejbLoad before the transaction begins and ejbStore just before committing the transaction (this will ensure that the bean and the database are always in sync). If you�d be allowed to write BMT then you�d obviously write code to perform begin and commit. Because of the load-and-store cycle it makes sense to start the transaction in ejbLoad and commit it in ejbStore. The problem is that you don�t call those methods directly. They are callback methods and are always invoked by the container. Neither you nor the bean can enforce that these two methods to be called in this order; they actually might not be called at all. It is very possible that only ejbLoad would be called and if you�d start the transaction here it will never commit. The reason above it�s actually Sun�s official standpoint and it should be more than enough to clarify your doubt. However there is another one that I personally always considered it being pretty good too. It is related to the fact that entity EJBs (unlike session EJBs) are re-entrant. Basically with entity EJBs, a scenario like this is possible:
If you�d start the transaction in A, then you�d have to start another one again (inside of the first tx), after B calls A. This would basically imply that your system would have to use nested transactions as well. On the other hand, J2EE doesn�t support nested transactions either. Regards.