How to do it...

There are three steps to completing this recipe. Let's perform them:

  1. Let's build a bean that will perform all the transactions we need:
@Stateful
@TransactionManagement
public class UserBean {

private ArrayList<Integer> actions;

@PostConstruct
public void init(){
actions = new ArrayList<>();
System.out.println("UserBean initialized");
}

public void add(Integer action){
actions.add(action);
System.out.println(action + " added");
}

public void remove(Integer action){
actions.remove(action);
System.out.println(action + " removed");
}

public List getActions(){
return actions;
}

@PreDestroy
public void destroy(){
System.out.println("UserBean will be destroyed");
}

@Remove
public void logout(){
System.out.println("User logout. Resources will be
released.");
}

@AfterBegin
public void transactionStarted(){
System.out.println("Transaction started");
}

@BeforeCompletion
public void willBeCommited(){
System.out.println("Transaction will be commited");
}

@AfterCompletion
public void afterCommit(boolean commited){
System.out.println("Transaction commited? " + commited);
}
}
  1. Then, create a test class to try it:
public class UserTest {

private EJBContainer ejbContainer;

@EJB
private UserBean userBean;

public UserTest() {
}

@Before
public void setUp() throws NamingException {
ejbContainer = EJBContainer.createEJBContainer();
ejbContainer.getContext().bind("inject", this);
}

@After
public void tearDown() {
ejbContainer.close();
}

@Test
public void test(){
userBean.add(1);
userBean.add(2);
userBean.add(3);
userBean.remove(2);
int size = userBean.getActions().size();
userBean.logout();
Assert.assertEquals(2, size);
}
}
  1. If you try this test, you should see this output (it will run automatically when you build the project):
 UserBean initialized
Transaction started
1 added
Transaction will be commited
Transaction commited? true
Transaction started
2 added
Transaction will be commited
Transaction commited? true
Transaction started
3 added
Transaction will be commited
Transaction commited? true
Transaction started
2 removed
Transaction will be commited
Transaction commited? true
Transaction started
Transaction will be commited
Transaction commited? true
Transaction started
User logout. Resources will be released.
UserBean will be destroyed
Transaction will be commited
Transaction commited? true
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.147.215