title: Why do I get a NullPointerException while trying to begin transaction?
body: <p>Before I was getting NullPointerException in this line </p>
  
  <pre><code>EntityManager manager = emf.createEntityManager();
  </code></pre>
  
  <p>but I fixed it by adding one line above</p>
  
  <pre><code>emf =  Persistence.createEntityManagerFactory("main");
  </code></pre>
  
  <p>Now I am getting NullPointerException in this line</p>
  
  <pre><code>transaction.begin();
  </code></pre>
  
  <p>I can't understand why. I was trying to take it from the try catch block but was getting the same result. Also in the finally I tried to add emf.close(); but the error doesn't get fixed. Also, I include @Named annotation because someone suggested me to do that. </p>
  
  <pre><code>import java.io.Serializable;
  import javax.inject.Named; 
  import javax.inject.Inject; 
  import java.sql.*;
  import javax.annotation.Resource;
  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.Persistence;
  import javax.persistence.PersistenceUnit;
  import javax.persistence.TypedQuery ; 
  import javax.transaction.UserTransaction;
  import javax.transaction.RollbackException; 
  import javax.persistence.criteria.*;
  import java.util.List;
  import java.util.*;
  
  @Named
  public class UserManager implements Serializable{
  
     @PersistenceUnit(unitName="main")
     private EntityManagerFactory emf;
  
     @Resource
     private UserTransaction transaction;
  
     public UserManager() {}
  
     public UserTransaction getTransaction() { return transaction; }
     public void setTransaction(UserTransaction transaction) { this.transaction = transaction; }
  
     public void addUser(User v) throws Exception {
      emf =  Persistence.createEntityManagerFactory("main");
          EntityManager manager = emf.createEntityManager();
          boolean commit;
          try {   
      transaction.begin();
          manager.joinTransaction();
      commit = false;
          try {
          manager.persist(v);
          transaction.commit();
          commit = true;
          }finally {
                  if(commit==false){
              transaction.rollback();
                  }
           }
          }finally {     
           manager.close();
               //emf.close();
      }
     }
  
  
  
  @Named("subBean")
  @RequestScoped
  public class UserBean implements Serializable{
  
     private List&lt;User&gt; users;
     private UserManager vm;
     private User v;
     private int total;
  
     public UserBean() {
        this.total= 0;
        users = new ArrayList&lt;User&gt;();
        vm = new UserManager();
        v = new User();
     }
  
     public String addUserAction() throws Exception {
        vm.addUser(v);
        users = getUsers();
        return "submit1";
  
     }
  
     //getters and setters 
  }
  </code></pre>