View Javadoc
1   package info.ejava.examples.ejb.tx.ejb;
2   
3   import info.ejava.examples.ejb.tx.bo.BeanCount;
4   
5   import javax.annotation.PostConstruct;
6   import javax.annotation.PreDestroy;
7   import javax.ejb.EJB;
8   import javax.ejb.Stateless;
9   import javax.ejb.TransactionAttribute;
10  import javax.ejb.TransactionAttributeType;
11  import javax.ejb.TransactionManagement;
12  import javax.ejb.TransactionManagementType;
13  import javax.persistence.EntityManager;
14  import javax.persistence.LockModeType;
15  import javax.persistence.PersistenceContext;
16  
17  import org.slf4j.Logger;
18  import org.slf4j.LoggerFactory;
19  
20  @Stateless
21  @TransactionManagement(TransactionManagementType.CONTAINER)
22  public class WarehouseTxEJB {
23      private static final Logger logger = LoggerFactory.getLogger(WarehouseTxEJB.class);
24      
25      @PersistenceContext(unitName="ejbtx-warehouse")
26      private EntityManager em;
27      
28      @EJB
29      private TxWatcherEJB txWatcher;
30  
31      @TransactionAttribute(TransactionAttributeType.REQUIRED)
32      @PostConstruct
33      public void init() {
34          logger.debug("*** {}:init({}) ***", getClass().getSimpleName(), super.hashCode());
35          txWatcher.watchTransaction(getClass(), super.hashCode());
36          updateBeanCount(1);
37      }
38      @TransactionAttribute(TransactionAttributeType.REQUIRED)
39      @PreDestroy
40      public void destroy() {
41          logger.debug("*** {}:destroy({}) ***", getClass().getSimpleName(), super.hashCode());
42          txWatcher.watchTransaction(getClass(), super.hashCode());
43          updateBeanCount(-1);
44      }
45      
46      /**
47       * This method will remove all data from all tables associated with the example
48       * @return
49       */
50      @TransactionAttribute(TransactionAttributeType.REQUIRED)
51      public int cleanup() {
52          String entities[] = new String[]{ "Product", "Shipment"};
53          int count=0;
54          for (String entity : entities) {
55              count+=em.createQuery(String.format("delete from %s", entity)).executeUpdate();
56          }
57          return count;
58      }
59      
60      private void updateBeanCount(int value) {
61          String beanName = getClass().getSimpleName();
62          BeanCount count=em.find(BeanCount.class, 
63                  beanName, 
64                  LockModeType.PESSIMISTIC_WRITE);
65          if (count!=null) {
66              count.setCount(count.getCount()+value);
67          } else {
68              count = new BeanCount(beanName);
69              count.setCount(value);
70              em.persist(count);
71          }
72          logger.debug("updatedBeanCount({}) to {}", count.getName(), count.getCount());
73      }
74  }