An Entity bean cannot use UserTransaction - however, it can force a rollback by calling setRollbackOnly() on the EJBContext which may work in your case.
Alternatively you could consider doing the check before modifying the bean's state with the first call and give the caller more choice about what happens to the transaction.
Thanks for your reply.
How does one gain access to the EJBContext?
Just for the sake of explanation: I'd prefer to trigger the rollback from within the entity bean after the bean's state has been modified, rather than before (as you suggest), because the business logic requirement can not be tested with 100% certainty until after the modification occurs.
Doh! Never mind about the EJBContext access question--I see it.
It's passed by the container in setEntityContext(ctx).
Setting the txn to rollback only is pretty traumatic - it causes the container to rollback all RM's (e.g. DBs), dump state for all beans involved and results in a TxnRollbackEx at the client.
If you can figure out how to perform the test without modifying state, you can throw an application exception. This has the advantage of telling the client exactly what the problem was, and without the side-effects in the container.
Either approach works - they just have different consequences.
I suppose I could perform the test prior to modifying the state provided I could lock the state of the RM so that it doesn't change between test and update.
Sheesh, all this abstract talk gives me a headache--let me translate into concrete terms.
The update I am performing is to the account number field of a General Ledger accounts table. The account number field is not a key field, but does have some key like characteristics, specifically, its value should be unique, hence the test. If I could perform the test prior to any update, AND be sure that no other updater can jump in and store the same account number value before I get to do my update, then that would be fine. Since I don't know how to (or if it is even possible to) lock the database from within the confines of the bean, I chose the route of doing the update, then checking to see if it resulted in duplicate account numbers and if so, rolling back the update.
If you know a technique for establishing a lock, I'd be very interested to see it.
Again, thanks for your replies.