package examples.entity.intro; import javax.ejb.Interceptors; import javax.ejb.Remote; import javax.ejb.Stateful; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityListener; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; /** * Stateful session bean facade for account entities, remotely accessible */ @Stateful @Remote(AccountInterface.class) public class AccountBean implements AccountInterface { /** The entity manager, injected by the container */ @PersistenceContext(type=PersistenceContextType.EXTENDED) private EntityManager manager; private Account account; @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void open(int accountNumber) { account = manager.find(Account.class, accountNumber); if(account == null) account = new Account(); account.ownerName = "anonymous"; account.accountNumber = accountNumber; manager.persist(account); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public int getBalance() { if(account==null) throw new IllegalStateException(); return account.balance; } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void deposit(int amount) { if(account==null) throw new IllegalStateException(); //manager = emf.createEntityManager(PersistenceContextType.EXTENDED); //account = manager.merge(account); account.balance += amount; //manager.flush(); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public int withdraw(int amount) { if(account==null) throw new IllegalStateException(); // manager.lock(account, LockMode.WRITE); if (amount > account.balance) { return 0; } else { account.balance -= amount; return amount; } } }