0

I have an entity class(Buyer) built automatically from database table, it has all the setter and getter. I also added a JSF managed Bean(BuyerBean) and an entitymanager in it.

@ManagedBean
@RequestScoped
public class BuyerBean {

    private EntityManager entitymanager;

    public BuyerBean() {
    }
    public void init(){
        entitymanager=Persistence.createEntityManagerFactory("WebApplication3").createEntityManager();
    }
    public void newrec(){

        entitymanager.getTransaction().begin();
            Buyer b =new Buyer();

            b.setBuyerId(66);

            entitymanager.persist(b);
            entitymanager.getTransaction().commit();

    }
}

And my JFS is like this, very simple just for testing:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <title>Facelet Title</title>
</h:head>
<h:body>
   <h:form>
       <h:commandButton value="click 1" action="#{buyerBean.newrec()}"/>
</h:form>
    </h:body>
</html>

I just get this error every time n my browser: java.lang.NullPointerException

is something wrong with my initiator? if there is, please write the piece of code

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
andrew
  • 13
  • 4

1 Answers1

0

Well, as NullPointerException is all you provided, I would say, there are two things I can see from this code :

1) entity manager may be null, in this case :

public void init() {      
if(entitymanager==null)
    entitymanager=Persistence.createEntityManagerFactory("WebApplication3").createEntityManager();
    }
public void newrec(){
init();
//some other code
}

2) Bean 'buyerbean' called from JSF may be null : Try renaming call to match class name - B to upper case :

action="#{BuyerBean.newrec()}

But these are only guesses. You need to provide more info.

milkamar
  • 443
  • 6
  • 16
  • thanks for replying, on first way I got this errorjavax.persistence.PersistenceException: No Persistence provider for EntityManager named WebApplication3: and on the second one:javax.el.PropertyNotFoundException: /index.xhtml @10,77 action="#{BuyerBean.newrec()}": Target Unreachable, identifier 'BuyerBean' resolved to null – andrew Mar 17 '17 at 22:46
  • Looked some documentation and it seems you need to define persistence unit in persistence.xml. It has name attribute, which you should insert as argument of createEntityManagerFactory method. Example is here : https://docs.oracle.com/cd/E19798-01/821-1841/bnbrj/index.html – milkamar Mar 18 '17 at 11:24