|
How to synchronize Session Bean state with the transactions |
|
|
A session Bean class can implement Session Synchronization interface only if bean needs to synchronize its state with the transactions. It has three methods.
afterBegin(): The afterBegin method notifies a session Bean instance that a new transaction has started, and that the subsequent business methods on the instance will be invoked in the context of the transaction.
afterCompletion(boolean committed): The afterCompletion method notifies a session Bean instance that a transaction commit protocol has completed, and tells the instance whether the transaction has been committed or rolled back.
beforeCompletion(): The beforeCompletion method notifies a session Bean instance that a transaction is about to be committed.
The following example will be more useful:
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.EJBObject;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.SessionSynchronization;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class synBean implements SessionBean, SessionSynchronization {
protected int count = 0; // state of the bean
protected int newcount = 0; // value inside Transaction, not committed.
protected String clientUser = null;
protected SessionContext sessionContext = null;
public void ejbCreate(String userid) {
count = 0;
newcount = count;
clientUser = userid;
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbRemove() {
}
public void setSessionContext(SessionContext sessionContext) {
this.sessionContext = sessionContext;
}
public void afterBegin() {
newcount = count;
}
public void beforeCompletion() {
// We can access the bean environment everywhere in the bean,
// for example here!
try {
InitialContext ictx = new InitialContext();
String value = (String) ictx.lookup("java:comp/env/property1");
// value should be the one defined in ejb-jar.xml
} catch (NamingException e) {
throw new EJBException(e);
}
}
public void afterCompletion(boolean committed) {
if (committed) {
count = newcount;
} else {
newcount = count;
}
}
public void write(int i) {
newcount = newcount + i;
return;
}
public int read() {
return newcount;
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.