Skip to content

Instantly share code, notes, and snippets.

@mojavelinux
Created December 21, 2010 18:25
Show Gist options
  • Save mojavelinux/750328 to your computer and use it in GitHub Desktop.
Save mojavelinux/750328 to your computer and use it in GitHub Desktop.
Seam TransactionWorker API
public class Consumer
{
private static final String[] GAME_TITLES = {"Game 1", "Game 2"};
@Inject
private TransactionWorkExecutor txWorkExecutor;
public void insertRecords()
{
txWorkExecutor.execute(new VoidTransactionWorker()
{
@Override public void doWorkInTransaction(TransactionContext ctx) throws Exception
{
for (String title : GAME_TITLES)
{
Game game = new Game(title);
ctx.getEntityManager().persist(game);
}
}
});
}
}
public class TransactionContext
{
private SeamTransaction tx;
private EntityManager em;
public TransactionContext(final SeamTransaction tx, final EntityManager em)
{
this.tx = tx;
this.em = em;
}
public EntityManager getEntityManager()
{
return em;
}
public SeamTransaction getTransaction()
{
return tx;
}
}
public interface TransactionWorker<T>
{
public T doWorkInTransactionAndReturn(TransactionContext ctx) throws Exception;
}
public class TransactionWorkExecutor
{
@Inject
private EntityManager em;
@Inject
private SeamTransaction tx;
public <T> T execute(TransactionWorker<T> worker) throws Exception
{
T result = null;
try
{
tx.begin();
result = worker.doWorkInTransactionAndReturn(new TransactionContext(tx, em));
tx.commit();
return result;
}
catch (Exception e)
{
// perhaps more detailed checking here
tx.rollback();
throw e;
}
}
}
public abstract class VoidTransactionWorker implements TransactionWorker<Void>
{
@Override
public Void doWorkInTransactionAndReturn(TransactionContext ctx) throws Exception
{
doWorkInTransaction(ctx);
return null;
}
public abstract void doWorkInTransaction(TransactionContext ctx) throws Exception;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment