In my Java SE/Java EE application I have a DAO interface to wrap around entity manager to allow simple CRUD operations. I also have an extended DAO interface that allows the simple CRUD operations to be performed as a batch operation, meaning all operations will be done under the same transaction. This allows me to roll back if one of the sequential CRUD operation fails.
public interface DomEntityManager {
void createEntity(Object aEntity) throws TransactionException;
void deleteEntity(Object aEntity) throws TransactionException;
void updateEntity(Object aEntity) throws TransactionException;
<T> T findById(int aId, Class<T> aClass);
<T> T getNewEntity(Class<T> aClass) throws TransactionException;
}
public interface BatchDomEntityManager extends DomEntityManager {
void execute(BatchTransation transaction);
}
public interface BatchTransaction {
public void run();
}
In this above design, what I am trying to achieve is, if the client calling code calls any of the DomEntityManager operations within the execute BatchTransaction method, then I want the operations to use a single transaction.
Currently, the Dom entity manager implementation has the straight forward implementation, where for each request an entity manager is created and new transaction is started and committed at the end of the request inside the DAO method. I am little stuck as how can I implement the share entity manager case. Should I be using ThreadLocal, in which case should the execute transaction block be executed in a separate thread. It's ok for me to block the execute call until the transaction is completed.
Thanks for any suggestion.