How do I insert or update 2 different Entity Beans within the same transaction?

Robert Castaneda

To easily achieve this, you can call both inserts from another bean, for example a Session Bean (if you are using the standard Session wraps Entity design pattern).

Lets say that both Entity Beans have defined create methods, and that the Session Bean has a method called insertEntities(). Inside the insertEntities() method, you would obtain handles to the approriate home interfaces and call create on each one. The trick here is on how you set up the transaction attributes.

You would like both of your Entity Beans to share the same transaction, and in this example, we can have the Session Bean as the initiator of the transaction.

If we set the insertEntites() method to have a Transaction Attribute of REQUIRED or REQUIRES_NEW, then we assure that a transaction will be present. (REQUIRED is generally more robust, since it allows this insertEntities() call to be part of an ongoing, larger transaction, but if one is not in progress, a new one will be created.) If we then set the Transaction Attributes for each of the Entity Beans to REQUIRED, then the same Transaction Context will be propagated from the Session Bean to both Entity Beans, achieving the result you are after.

[Note that this works no matter which Persistence method (CMP or BMP) the Entity Beans use.]