Guest User

Untitled

a guest
Jun 18th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. package utils;
  2.  
  3. import io.ebean.Ebean;
  4. import io.ebean.Transaction;
  5. import org.aopalliance.intercept.MethodInterceptor;
  6. import org.aopalliance.intercept.MethodInvocation;
  7.  
  8. import java.lang.reflect.Method;
  9.  
  10. /**
  11. * @author James Lin
  12. */
  13. public class EbeanTransactionalInterceptor implements MethodInterceptor {
  14.  
  15. private static final ThreadLocal<Integer> txCountLocal = ThreadLocal.withInitial(() -> 0);
  16.  
  17. @Override
  18. public Object invoke(MethodInvocation invocation) throws Throwable {
  19. Method method = invocation.getMethod();
  20. Transactional annotation = method.getAnnotation(Transactional.class);
  21. boolean readOnly = annotation.readOnly();
  22. String dbName = annotation.dbName().name().toLowerCase();
  23.  
  24. int txCount = txCountLocal.get();
  25. if(txCount == 0) {
  26. txCountLocal.set(++txCount);
  27. Transaction tx = null;
  28. try {
  29. tx = Ebean.getServer(dbName).beginTransaction();
  30. tx.getConnection().setAutoCommit(false);
  31. tx.setReadOnly(readOnly);
  32. Object result = invocation.proceed();
  33. tx.commit();
  34. return result;
  35. }
  36. finally {
  37. txCountLocal.remove();
  38. if(tx != null) {
  39. tx.end();
  40. }
  41. }
  42. }
  43. else {
  44. txCountLocal.set(++txCount);
  45. try {
  46. return invocation.proceed();
  47. }
  48. finally {
  49. txCountLocal.set(--txCount);
  50. }
  51. }
  52. }
  53. }
  54.  
  55. package utils;
  56.  
  57. import java.lang.annotation.ElementType;
  58. import java.lang.annotation.Retention;
  59. import java.lang.annotation.RetentionPolicy;
  60. import java.lang.annotation.Target;
  61.  
  62. /**
  63. * @author James Lin
  64. */
  65. @Target({ElementType.TYPE, ElementType.METHOD})
  66. @Retention(RetentionPolicy.RUNTIME)
  67. public @interface Transactional {
  68.  
  69. boolean readOnly() default false;
  70. }
Add Comment
Please, Sign In to add comment