Domanda

With Java EE I need to use a stateful session Bean.

@Stateful
@TransactionManagement(TransactionManagementType.BEAN)
public class FacadeExercice extends AbstractFacade<EntityBeanExercice>
  implements IFacadeExercice {

@PersistenceContext(unitName = "GestionCours-ejbPU")
private EntityManager em;
@Resource
private UserTransaction transaction;
private int lastChange;
private int connections;

[...]

@Override
public EntityBeanExercice find(Object id) {
    EntityBeanExercice ex = null;
    connections += 5;
    try {
        transaction.begin();
        ex = super.find(id);
        lastChange = ex.getLastChange();
        transaction.commit();
    } catch (Exception ex1) {
        Logger.getLogger(FacadeExercice.class.getName()).log(
          Level.SEVERE, null, ex1);
    }
    return ex;
}
}

But every time I enter in my bean, the connections variable is set to 0.

I have no Idea where I can search a solution.

È stato utile?

Soluzione

This problem can arise in these situations:

  • The lifetime of a SFSB is connected to the lifetime of its client.

Your SFSB works fine, if you have a command line client for example. When the command line application is terminated, the SFSB is removed as well.

If the SFSB is used by a JSP/servlet for example, it's lifetime ends, when the HTTP request is completed. If it is to survive the HTTP request, you have to put it's handle in the HTTP session: After you have got an instance from a JNDI lookup, you should put that instance as an attribute in the HttpSession. The next HTTP request to use this SFSB must get the handle from the HttpSession.

  • Each JNDI lookup returns a new instance

A quote from EJB 3.1, 4.6 Stateful Session Bean State Diagram

When a stateful session bean is looked up or otherwise obtained through the explicit JNDI lookup mechanisms, the container must provide a new stateful session bean instance, as required by the Java EE specification (Section “Java Naming and Directory Interface (JNDI) Naming Context” [12]).

So you should not lookup the SFSB more than one time.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top