title: JPA Lazy Loading
body: <p>I have a problem with lazy loading property in JPA entity. I read many similar questions, but they are related to spring or hibernate and their answears are either not applicable or helpful.</p>
  
  <p>The application is JEE with JPA2.1 running on Wildfly application server. There are two entities, DAO session bean and servlet that puts it together:</p>
  
  <pre><code>@Entity
  @Table(name = "base_user")
  public class User implements Serializable {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "id")
      int id;
  
      @OneToMany(fetch=FetchType.LAZY, mappedBy="user")
      List&lt;OAuthLogin&gt; oauthLogins;
  
  }
  
  
  @Entity
  @Table(name = "oauth_login")
  public class OAuthLogin implements Serializable {
      @ManyToOne
      @JoinColumn(name="user_id", nullable=false)
      User user;
  }
  
  
  @Stateless(name = "UserDAOEJB")
  public class UserDAO {
      @PersistenceContext(unitName="OAUTHDEMO")
      EntityManager em;
  
      public User findById(int id) {
          User entity;
      entity = em.find(User.class, id);
          return entity;
      }
  }
  
  
  public class SaveUserServlet extends HttpServlet {
      @EJB
      UserDAO userDAO;
  
      @Transactional
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          User user = new User(name);
          user.setEmail(email);
          System.out.println("Persisting user " + user);
          userDAO.persist(user);
  
          OAuthLogin fbLogin1 = new OAuthLogin(user, OAuthProvider.FACEBOOK, "1501791394");
          loginDAO.persist(fbLogin1);
  
          User user2 = userDAO.findById(user.getId());
          List&lt;OAuthLogin&gt; oauthLogins = user2.getOauthLogins();
  </code></pre>
  
  <p>When I run this code, it fails with:</p>
  
  <pre><code>org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: cz.literak.demo.oauth.model.entity.User.oauthLogins, could not initialize proxy - no Session
  org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:572)
  org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:212)
  org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:551)
  org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:140)
  org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:294)
  cz.literak.demo.oauth.servlets.SaveUserServlet.doPost(SaveUserServlet.java:66)
  </code></pre>
  
  <p>I used very similar pattern with WebLogic/JPA1 and it ran smoothly. Any idea? Thanks</p>
  
  <p>PS. this is a JPA application, I do not have hibernate session etc.</p>