Reputation: 257
I'm developing a JEE application where each request done to "facade" beans should run a single transaction.
Basicly, in each method, I could do it like this:
@Override
public void updateSalaries(float factor)
{
initializeTransaction();
// Actual business code...
commitTransaction();
}
Where ùpdateSalaries()is a method invoked by the client, and where
initializeTransaction()and
commitTransaction()` respectively take care of getting/starting/committing/rolling back (if necessary) the transaction.
Unfortunately, the transaction management should be more transparent: something developers should not care about when writing business methods.
Therefore, some way to "decorate" these business methods would be nice, but I can't think of a possible way to do that.
Another possible solution I thought of would be to handle it in a central DataAccessBean
class, where I would start the transaction on @PostConstruct
and commit it on @PreDestroy
:
@Stateless
public class DataAccessBean implements IDataAccessBean
{
@PostConstruct
public void initializeTransaction() { /* ... */ }
@PreDestroy
public void endTransaction() { /* ... */ }
@Override
public <T implements Serializable> T getObjectById(
Class<T> objectType, Object key) { /* ... */ }
@Override
public void saveObject(Serializable object) { /* ... */ }
}
I'm not sure though, if I can rely on that mechanism. An important question would also be, what type of bean I'd need: I doubt a stateful bean would be suitable as the transaction is per-request and not per-session. Maybe a stateless bean would be a good option, but AFAIK a stateless bean might not be destroyed when a request completes (if it resides in a stateless bean pool).
Two little constraints:
Thanks for the suggestions.
Upvotes: 0
Views: 127
Reputation: 723
What you need is addressed by Java Transaction API (JTA). From the JEE6 Tutorial (Part VIII - Chapter 42):
The Java Transaction API (JTA) allows applications to access transactions in amanner that is independent of speciic implementations. JTA speciies standard Java interfaces between a transactionmanager and the parties involved in a distributed transaction system: the transactional application, the Java EE server, and themanager that controls access to the shared resources afected by the transactions.
You want to use the Container-Managed Transaction. In this strategy you just need decorate the beans/methods with the appropriate transaction attribute i.e.:
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void myMethod() {
...
}
The design of your service layer must carefully address the transaction life cycle in case your have services of services (nested service calls).
Upvotes: 1