In Mastering
EJB book i have found following but i am not able to understand
it.
Perhaps one of the most misunderstood concepts in EJB is how transactions relate to entity beans. Let�s explore this concept.
When you call an entity bean in a transaction, the first action that happens is the entity bean needs to load database data through the ejbLoad() method,
which acquires locks in the database and ensures the entity bean cache is
consistent. Then one or more business methods are called. When the
transaction is committed, the entity bean�s ejbStore() method is called, which writes all updates to the database and releases the locks. A transaction should thus span the ejbLoad() business methods, and the final ejbStore(), so that if any one of those operations fail, they all fail.
If we were to use bean-managed transactions, we would write code to
perform begin() and commit() methods inside our bean (perhaps around the
JDBC code). Perhaps we would start the transaction in ejbLoad(), and then
commit the transaction in ejbStore(). The problem, though, is that you do not call your own ejbLoad() or ejbStore() methods�the container does. The bean cannot enforce that these methods happen in this order, if at all. Therefore if you started a transaction in ejbLoad(), the transaction may never complete.
Because of this, bean-managed transactions are illegal for entity beans.
Entity beans must use declarative transactions. Session beans or messagedriven
beans can use bean-managed transactions because a session bean can
load database data, perform operations on that data, and then store that data; all in a single method call, and thus is in direct control over the transaction.
A corollary of this discussion is that entity beans do not load and store their data on every method call; rather, they load and store their data on every transaction. If your entity beans are not performing well, it could be because a transaction is happening on each method call, and thus a database read/write is happening on every get/set method. The solution is to make sure your transactions begin earlier and end later, perhaps encompassing many entity bean method calls. By properly controlling the duration of your transactions with transaction attributes (as we will see later in this chapter), you can control when database reads and writes happen with entity beans.