title: @EJB in @ViewScoped @ManagedBean causes java.io.NotSerializableException
body: <p>I've read <a href="https://stackoverflow.com/questions/3037722/ejb-in-viewscoped-managed-bean-causes-java-io-notserializableexception">@EJB in @ViewScoped managed bean causes java.io.NotSerializableException</a>, but my state saving setting is <code>server</code>.</p>
  
  <p>Here is what I have:</p>
  
  <p><code>web.xml</code>:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"&gt;
      &lt;display-name&gt;sispra&lt;/display-name&gt;
      &lt;welcome-file-list&gt;
          &lt;welcome-file&gt;index.jsf&lt;/welcome-file&gt;
      &lt;/welcome-file-list&gt;
      &lt;servlet&gt;
          &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
          &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
          &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
      &lt;/servlet&gt;
      &lt;servlet-mapping&gt;
          &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
          &lt;url-pattern&gt;*.jsf&lt;/url-pattern&gt;
      &lt;/servlet-mapping&gt;
  
      &lt;filter&gt;
          &lt;filter-name&gt;PrimeFaces FileUpload Filter&lt;/filter-name&gt;
          &lt;filter-class&gt;org.primefaces.webapp.filter.FileUploadFilter&lt;/filter-class&gt;
      &lt;/filter&gt;
      &lt;filter-mapping&gt;
          &lt;filter-name&gt;PrimeFaces FileUpload Filter&lt;/filter-name&gt;
          &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
      &lt;/filter-mapping&gt;
  
      &lt;context-param&gt;
          &lt;param-name&gt;javax.faces.PROJECT_STAGE&lt;/param-name&gt;
          &lt;param-value&gt;Development&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt;
          &lt;param-value&gt;server&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;facelets.BUILD_BEFORE_RESTORE&lt;/param-name&gt;
          &lt;param-value&gt;true&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;org.apache.myfaces.ALLOW_JAVASCRIPT&lt;/param-name&gt;
          &lt;param-value&gt;true&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;org.apache.myfaces.PRETTY_HTML&lt;/param-name&gt;
          &lt;param-value&gt;true&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;org.apache.myfaces.DETECT_JAVASCRIPT&lt;/param-name&gt;
          &lt;param-value&gt;false&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;org.apache.myfaces.AUTO_SCROLL&lt;/param-name&gt;
          &lt;param-value&gt;true&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;context-param&gt;
          &lt;param-name&gt;primefaces.THEME&lt;/param-name&gt;
          &lt;param-value&gt;glass-x&lt;/param-value&gt;
      &lt;/context-param&gt;
      &lt;security-constraint&gt;
          &lt;web-resource-collection&gt;
              &lt;web-resource-name&gt;Secure Application&lt;/web-resource-name&gt;
              &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
              &lt;http-method&gt;GET&lt;/http-method&gt;
              &lt;http-method&gt;POST&lt;/http-method&gt;
          &lt;/web-resource-collection&gt;
          &lt;auth-constraint&gt;
              &lt;role-name&gt;user&lt;/role-name&gt;
          &lt;/auth-constraint&gt;
      &lt;/security-constraint&gt;
      &lt;login-config&gt;
          &lt;auth-method&gt;BASIC&lt;/auth-method&gt;
          &lt;realm-name&gt;fileRealm&lt;/realm-name&gt;
      &lt;/login-config&gt;
      &lt;session-config&gt;
          &lt;session-timeout&gt;30&lt;/session-timeout&gt;
      &lt;/session-config&gt;
      &lt;security-role&gt;
          &lt;role-name&gt;user&lt;/role-name&gt;
      &lt;/security-role&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p><code>customer.xhtml</code>:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:p="http://primefaces.org/ui"&gt;      
  
      &lt;h:head&gt;
          &lt;title&gt;TODO supply a title&lt;/title&gt;
      &lt;/h:head&gt;
  
      &lt;h:body&gt;
  
          &lt;p:growl id="messages"/&gt;
  
          &lt;h:form&gt;
  
              &lt;p:commandButton actionListener="#{customerController.create}" value="save" update="@form :messages"/&gt;
  
              &lt;p:panel&gt;
                  &lt;f:facet name="header"&gt;
                      &lt;h:outputText value="Details"/&gt;
                  &lt;/f:facet&gt;
  
                  &lt;h:panelGrid columns="3"&gt;
  
                      &lt;h:outputLabel for="name" value="#{bundle['person.name']}"/&gt;
                      &lt;p:inputText id="name" label="#{bundle['person.name']}" value="#{customerController.selected.name}"/&gt;
                      &lt;p:message for="name"/&gt;
  
                      &lt;h:outputLabel for="surname" value="#{bundle['person.surname']}"/&gt;
                      &lt;p:inputText id="surname" label="#{bundle['person.surname']}" value="#{customerController.selected.surname}"/&gt;
                      &lt;p:message for="surname"/&gt;
  
                  &lt;/h:panelGrid&gt;
              &lt;/p:panel&gt;
  
          &lt;/h:form&gt;
  
      &lt;/h:body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><code>CustomerController.java</code>:</p>
  
  <pre><code>package it.shape.sispra.controllers;
  
  import it.shape.sispra.ejb.PersonFacade;
  import it.shape.sispra.entities.Customer;
  import javax.ejb.EJB;
  import javax.faces.bean.ManagedBean;
  import javax.faces.bean.ViewScoped;
  
  @ManagedBean
  @ViewScoped
  public class CustomerController extends AbstractController&lt;Customer&gt;
  {
      private static final long serialVersionUID = 134755304347034L;
  
      @EJB
      private PersonFacade facade;
  
      public CustomerController()
      {
          super(Customer.class);
      }
  
      @Override
      public PersonFacade getFacade()
      {
          return facade;
      }
  }
  </code></pre>
  
  <p><code>PersonFacade.java</code>:</p>
  
  <pre><code>package it.shape.sispra.ejb;
  
  import it.shape.sispra.entities.Person;
  import javax.ejb.Stateless;
  
  @Stateless
  public class PersonFacade extends AbstractFacade&lt;Person&gt;
  {
      private static final long serialVersionUID = 4357823648345L;
  
      public PersonFacade()
      {
          super(Person.class);
      }
  
  }
  </code></pre>
  
  <p>AbstractFacade.java:</p>
  
  <pre><code>package it.shape.sispra.ejb;
  
  import it.shape.sispra.entities.AbstractEntity;
  import java.io.Serializable;
  import java.util.List;
  import javax.persistence.EntityManager;
  import javax.persistence.PersistenceContext;
  import javax.persistence.Query;
  import javax.persistence.TypedQuery;
  import javax.persistence.criteria.CriteriaQuery;
  import javax.persistence.criteria.Root;
  import org.eclipse.persistence.jpa.JpaHelper;
  import org.eclipse.persistence.queries.QueryByExamplePolicy;
  import org.eclipse.persistence.queries.ReadAllQuery;
  import org.eclipse.persistence.queries.ReadObjectQuery;
  
  public abstract class AbstractFacade&lt;T extends AbstractEntity&gt; implements Serializable
  {
      private static final long serialVersionUID = 12467890452346123L;
  
      @PersistenceContext(unitName = "sispra")
      private EntityManager em;
  
      private final Class&lt;T&gt; entityClass;
  
      public AbstractFacade(Class&lt;T&gt; entityClass)
      {
          this.entityClass = entityClass;
      }
  
      public EntityManager getEntityManager()
      {
          return em;
      }
  
      public void create(T entity)
      {
          getEntityManager().persist(entity);
      }
  
      public void edit(T entity)
      {
          getEntityManager().merge(entity);
      }
  
      public void remove(T entity)
      {
          getEntityManager().remove(getEntityManager().merge(entity));
      }
  
      public void refresh(T entity)
      {
          getEntityManager().refresh(entity);
      }
  
      public T find(Object id)
      {
          return getEntityManager().find(entityClass, id);
      }
  
      public List&lt;T&gt; findAll()
      {
          CriteriaQuery&lt;T&gt; cq = getEntityManager().getCriteriaBuilder().createQuery(entityClass);
          cq.select(cq.from(entityClass));
  
          return getEntityManager().createQuery(cq).getResultList();
      }
  
      public List&lt;T&gt; findRange(int first, int max)
      {
          CriteriaQuery&lt;T&gt; cq = getEntityManager().getCriteriaBuilder().createQuery(entityClass);
          cq.select(cq.from(entityClass));
  
          TypedQuery&lt;T&gt; q = getEntityManager().createQuery(cq);
          q.setMaxResults(max);
          q.setFirstResult(first);
  
          return q.getResultList();
      }
  
      public int count()
      {
          CriteriaQuery&lt;Long&gt; cq = getEntityManager().getCriteriaBuilder().createQuery(Long.class);
          Root&lt;T&gt; rt = cq.from(entityClass);
          cq.select(getEntityManager().getCriteriaBuilder().count(rt));
          TypedQuery&lt;Long&gt; q = getEntityManager().createQuery(cq);
          return q.getSingleResult().intValue();
      }
  
      @SuppressWarnings("unchecked")
      public T findByExample(T entity)
      {
          // Create a native EclipseLink query using QBE policy
          QueryByExamplePolicy policy = new QueryByExamplePolicy();
          policy.addSpecialOperation(String.class, "like");
  
          ReadObjectQuery roq = new ReadObjectQuery(entity, policy);
  
          // Wrap the native query in a standard JPA Query and execute it
          Query query = JpaHelper.createQuery(roq, getEntityManager());
  
          return (T) query.getSingleResult();
      }
  
      @SuppressWarnings("unchecked")
      public List&lt;T&gt; findAllByExample(T entity)
      {
          // Create a native EclipseLink query using QBE policy
          QueryByExamplePolicy policy = new QueryByExamplePolicy();
          policy.addSpecialOperation(String.class, "like");
  
          ReadAllQuery raq = new ReadAllQuery(entity, policy);
  
          // Wrap the native query in a standard JPA Query and execute it
          Query query = JpaHelper.createQuery(raq, getEntityManager());
  
          return query.getResultList();
      }
  
      @SuppressWarnings("unchecked")
      public List&lt;T&gt; findByExample(T entity, int start, int max)
      {
          // Create a native EclipseLink query using QBE policy
          QueryByExamplePolicy policy = new QueryByExamplePolicy();
          policy.addSpecialOperation(String.class, "like");
  
          ReadAllQuery raq = new ReadAllQuery(entity, policy);
  
          // Wrap the native query in a standard JPA Query and execute it
          Query query = JpaHelper.createQuery(raq, getEntityManager());
          query.setFirstResult(start);
          query.setMaxResults(max);
  
          return query.getResultList();
      }
  
      public int countByExample(T entity)
      {
          //TODO find a better way...
          return findAllByExample(entity).size();
      }
  }
  </code></pre>
  
  <p>and this is the stacktrace:</p>
  
  <pre><code>GRAVE: Exiting serializeView - Could not serialize state: com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate
  java.io.NotSerializableException: com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
    at java.util.HashMap.writeObject(HashMap.java:1001)
    at sun.reflect.GeneratedMethodAccessor45.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1469)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1346)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1154)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
    at java.util.HashMap.writeObject(HashMap.java:1001)
    at sun.reflect.GeneratedMethodAccessor45.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1469)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1346)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1154)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
    at org.apache.myfaces.renderkit.ServerSideStateCacheImpl.serializeView(ServerSideStateCacheImpl.java:357)
    at org.apache.myfaces.renderkit.ServerSideStateCacheImpl.saveSerializedViewInServletSession(ServerSideStateCacheImpl.java:220)
    at org.apache.myfaces.renderkit.ServerSideStateCacheImpl.saveSerializedView(ServerSideStateCacheImpl.java:798)
    at org.apache.myfaces.renderkit.html.HtmlResponseStateManager.saveState(HtmlResponseStateManager.java:127)
    at org.apache.myfaces.application.StateManagerImpl.saveView(StateManagerImpl.java:166)
    at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1554)
    at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:281)
    at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:85)
    at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:662)
  </code></pre>
  
  <p>I know I can workaround this by declaring <code>PersonFacade</code> as <code>transient</code> and use JNDI to get EJB reference after recontruction, but I really dislike this approach.</p>
  
  <p>Is it possible that Glassfish 3.1.1 provides non-serializable EJBs? Is there a way to use <code>@EJB</code> and <code>@ViewScoped</code> together?</p>
  
  <p><strong>update:</strong>
  i found that this is a MyFaces related issue, all is working fine using mojarra</p>