Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package utils;
- import io.ebean.Ebean;
- import io.ebean.Transaction;
- import org.aopalliance.intercept.MethodInterceptor;
- import org.aopalliance.intercept.MethodInvocation;
- import java.lang.reflect.Method;
- /**
- * @author James Lin
- */
- public class EbeanTransactionalInterceptor implements MethodInterceptor {
- private static final ThreadLocal<Integer> txCountLocal = ThreadLocal.withInitial(() -> 0);
- @Override
- public Object invoke(MethodInvocation invocation) throws Throwable {
- Method method = invocation.getMethod();
- Transactional annotation = method.getAnnotation(Transactional.class);
- boolean readOnly = annotation.readOnly();
- String dbName = annotation.dbName().name().toLowerCase();
- int txCount = txCountLocal.get();
- if(txCount == 0) {
- txCountLocal.set(++txCount);
- Transaction tx = null;
- try {
- tx = Ebean.getServer(dbName).beginTransaction();
- tx.getConnection().setAutoCommit(false);
- tx.setReadOnly(readOnly);
- Object result = invocation.proceed();
- tx.commit();
- return result;
- }
- finally {
- txCountLocal.remove();
- if(tx != null) {
- tx.end();
- }
- }
- }
- else {
- txCountLocal.set(++txCount);
- try {
- return invocation.proceed();
- }
- finally {
- txCountLocal.set(--txCount);
- }
- }
- }
- }
- package utils;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- /**
- * @author James Lin
- */
- @Target({ElementType.TYPE, ElementType.METHOD})
- @Retention(RetentionPolicy.RUNTIME)
- public @interface Transactional {
- boolean readOnly() default false;
- }
Add Comment
Please, Sign In to add comment