Advertisement
Guest User

Untitled

a guest
Sep 19th, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. public static void main(String args[])
  2. {
  3. Weld weld = new Weld();
  4. WeldContainer container = weld.initialize();
  5.  
  6. ShopCar sc = container.instance().select(ShopCar.class).get();
  7. sc.execute();
  8. weld.shutdown();
  9. }
  10.  
  11. /**
  12. *
  13. * @author vFreitas
  14. * @param <T> The type T
  15. */
  16. public class JpaDAO<T> implements DAO<T>, Serializable
  17. {
  18. /* The EntityManager of my connection */
  19. private final EntityManager em;
  20. /* The class to be persist */
  21. private final Class<T> classe;
  22.  
  23. private ThreadLocal<EntityManager> threadLocal;
  24.  
  25. /* Builder */
  26. /**
  27. *
  28. * @author info1
  29. * @param classe The class to that will represent T
  30. * @param em A new instance of EntityManager
  31. */
  32. public JpaDAO(Class<T> classe, EntityManager em)
  33. {
  34. this.classe = classe;
  35. this.em = em;
  36. threadLocal = new ThreadLocal<>();
  37. threadLocal.set(em);
  38. }
  39.  
  40. @Override
  41. @Transacional
  42. public void save(T entity)
  43. {
  44. //em.getTransaction().begin();
  45. em.persist(entity);
  46. //em.getTransaction().commit();
  47. }
  48.  
  49. ...
  50.  
  51. public class DAOFactory<T>
  52. {
  53. @Inject @MyDatabase private EntityManager em;
  54.  
  55. @SuppressWarnings({ "rawtypes", "unchecked" })
  56. @Produces
  57. public JpaDAO<T> createJpaDAO(InjectionPoint injectionPoint) throws
  58. ClassNotFoundException
  59. {
  60. ParameterizedType type = (ParameterizedType) injectionPoint.getType();
  61. Class classe = (Class) type.getActualTypeArguments()[0];
  62. return new JpaDAO<>(classe,em);
  63. }
  64. }
  65.  
  66. @Target({ ElementType.METHOD, ElementType.TYPE })
  67. @Retention(RetentionPolicy.RUNTIME)
  68. @InterceptorBinding
  69. public @interface Transacional
  70. {
  71.  
  72. }
  73.  
  74. @Interceptor
  75. @Transacional
  76. public class TransacionalInterceptor
  77. {
  78.  
  79. @Inject @MyDatabase
  80. private EntityManager manager;
  81.  
  82. @Inject private ThreadLocal<EntityManager> threadLocal;
  83.  
  84. Logger logger = LoggerFactory.getLogger(TransacionalInterceptor.class);
  85.  
  86. @AroundInvoke
  87. public Object invoke(InvocationContext context) throws Exception
  88. {
  89. manager = threadLocal.get();
  90. //EntityTransaction trx = manager.getTransaction();
  91. if(!manager.getTransaction().isActive())
  92. {
  93. manager.getTransaction().begin();
  94. System.out.println("Starting transaction");
  95. Object result = context.proceed();
  96. manager.getTransaction().commit();
  97. System.out.println("Committing transaction");
  98. return result;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement