1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import net.wessendorf.logger.JulFactory;
/**
* AOP via Java EE - (very) simple Interceptor
* to use (declarative) Transactions via a custom
* <code>Transactional</code> annotation, like you
* know from Spring Framework.
*
* @author Apache OpenWebBeans team (reservation example)
*/
@Transactional
@javax.interceptor.Interceptor
public class TransactionalInterceptor implements Serializable
{
private static final long serialVersionUID = 1L;
private @Inject EntityManager entityManager;
private static Logger LOG = JulFactory.createLogger(TransactionalInterceptor.class);
@AroundInvoke
public Object invoke(InvocationContext context) throws Exception
{
EntityTransaction transaction = entityManager.getTransaction();
try
{
if (!transaction.isActive())
{
transaction.begin();
}
return context.proceed();
}
catch (Exception e)
{
LOG.log(Level.SEVERE, "Exception in transactional method call", e);
if (transaction != null)
{
transaction.rollback();
}
throw e;
}
finally
{
if (transaction != null && transaction.isActive())
{
transaction.commit();
}
}
}
} |
Partager