2 Replies Latest reply on Feb 12, 2009 12:29 PM by tchello

    Another NULL Pointer Exception on Entity Manager =/

    tchello

      Hi!
      I've been looking so far on google but i could not find it.
      I'm still learning EJB3 and trying to do a simple example to discovery how it works (including annotations and application servers like JBoss 4.2.2).

      Could you help-me?
      Here is the code samples:

      A simple entity

      package EJBClasses;
      
      import java.io.Serializable;
      import javax.persistence.Column;
      import javax.persistence.Entity;
      import javax.persistence.GeneratedValue;
      import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.Table;
      
      /**
       *
       * @author Tchello
       */
      @Entity
      @Table(name="endereco")
      public class Endereco implements Serializable {
      
       //--------------------------------------------------------------------------
       private Integer codigo;
       private String rua;
       private Integer numero;
       private String bairro;
       private String cep;
       private String cidade;
       private String estado;
       private String pais;
       //--------------------------------------------------------------------------
       //--------------------------------------------------------------------------
       /** Creates a new instance of Endereco */
       public Endereco() {
       }
       //--------------------------------------------------------------------------
       @Id
       @GeneratedValue(strategy=GenerationType.SEQUENCE)
       @Column(name="codigo")
       public Integer getCodigo() {
       return codigo;
       }
       //--------------------------------------------------------------------------
       public void setCodigo(Integer codigo) {
       this.codigo = codigo;
       }
       //--------------------------------------------------------------------------
       @Column(name="rua")
       public String getRua() {
       return rua;
       }
       //--------------------------------------------------------------------------
       public void setRua(String rua) {
       this.rua = rua;
       }
       //--------------------------------------------------------------------------
       @Column(name="numero")
       public Integer getNumero() {
       return numero;
       }
       //--------------------------------------------------------------------------
       public void setNumero(Integer numero) {
       this.numero = numero;
       }
       //--------------------------------------------------------------------------
       @Column(name="bairro")
       public String getBairro() {
       return bairro;
       }
       //--------------------------------------------------------------------------
       public void setBairro(String bairro) {
       this.bairro = bairro;
       }
       //--------------------------------------------------------------------------
       @Column(name="cep")
       public String getCep() {
       return cep;
       }
       //--------------------------------------------------------------------------
       public void setCep(String cep) {
       this.cep = cep;
       }
       //--------------------------------------------------------------------------
       @Column(name="cidade")
       public String getCidade() {
       return cidade;
       }
       //--------------------------------------------------------------------------
       public void setCidade(String cidade) {
       this.cidade = cidade;
       }
       //--------------------------------------------------------------------------
       @Column(name="estado")
       public String getEstado() {
       return estado;
       }
       //--------------------------------------------------------------------------
       public void setEstado(String estado) {
       this.estado = estado;
       }
       //--------------------------------------------------------------------------
       @Column(name="pais")
       public String getPais() {
       return pais;
       }
       //--------------------------------------------------------------------------
       public void setPais(String pais) {
       this.pais = pais;
       }
       //--------------------------------------------------------------------------
      }
      


      My Entity Manager and interfaces:
      @Stateless
      public class ManagerBean implements Manager,ManagerRemote{
      
       @PersistenceContext(unitName="MyPostgresDS")//unitName="myunit"
       private EntityManager em;
      
       /** Creates a new instance of ManagerBean */
       public ManagerBean() {
       }
       public void salvar(){
       Endereco endereco = new Endereco();
       //endereco.setCodigo(3);
       endereco.setBairro("vila do fulano");
       endereco.setCep("1232413");
       endereco.setCidade("Campinas");
       endereco.setEstado("Sao Paulo");
       endereco.setNumero(123);
       endereco.setPais("Brasil");
       endereco.setRua("Rua dumal");
      
       System.out.println("Persisting...");
      
       em.getTransaction().begin();
       em.persist(endereco);
       em.getTransaction().commit();
       }
      }
      
      


      The main:
      public class EntityInstructorClient {
      
       public static void main(String args[]){
       System.out.println("Main...");
       ManagerBean bean = new ManagerBean();
       bean.salvar();
       }
      }
      


      I think the error could be on xml files, what i'm not familiar yet.
      Here:
      persistence.xml
      <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
       <persistence-unit name="myunit" transaction-type ="JTA">
       <jta-data-source>java:MyPostgresDS</jta-data-source>
       <class>EJBClasses.ManagerBean</class>
       <properties>
       <propertie name="org.hibernate.hbm2ddl" value="create-table"/>
       <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
       <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
       </properties>
       </persistence-unit>
      </persistence>
      

      jboss.xml
      <datasources>
       <local-tx-datasource>
       <jndi-name>MyPostegresDS</jndi-name>
       <connection-url>jdbc/:postgresql://192.168.0.200:5432/netejb</connection-url>
       <driver-class>org.postgresql.Driver</driver-class>
       <user-name>postgres</user-name>
       <password>postgres</password>
       <min-pool-size>5</min-pool-size>
       <max-pool-size>20</max-pool-size>
       <idle-timeout-minutes>5</idle-timeout-minutes>
       <metadata>
       <type-mapping>PostgreSQL</type-mapping>
       </metadata>
       </local-tx-datasource>
      </datasources>
      


      All i got is:

      Exception in thread "main" java.lang.NullPointerException
      at EJBClasses.ManagerBean.salvar(ManagerBean.java:42)
      at EJBClasses.EntityInstructorClient.main(EntityInstructorClient.java:23)
      Java Result: 1


      What am i missing? I'm trying so hard but there is so many things to learn, can someone help me?
      I am using NetBeans 5.5.1, JBoss 4.2.2 and EJB 3 (i cant change the versions).

      Thank you!

        • 1. Re: Another NULL Pointer Exception on Entity Manager =/
          peterj

          You are running a standalone client and loading ManagerBean as a POJO. In that environment annotations are not processed.

          If you want to get this to work you need to package ManagerBean, Endereco and persistence.xml in an EJB JAR file and deploy it and then convert your client code to a servlet (for example), and invoke the EJB from there via JNDI.

          • 2. Re: Another NULL Pointer Exception on Entity Manager =/
            tchello

            Ok, as you sad: i createad a new project respecting all those rules (i hope).
            Lets see:

            JSP file:

            <%@ page language="java"
            isThreadSafe="false"
            import="javax.naming.*"
            import="javax.rmi.PortableRemoteObject"
            import="org.interfaces.*"
            import="org.classes.*"
            %>
            <html>
             <head>
             <title>JSP Page</title>
             </head>
             <body>
             <%
             ManagerRemote mn = null;
             InitialContext ic = null;
            
             try {
             out.print("Starting...<BR>");
             ic = new InitialContext();
            
             out.print("Initial instanced<BR>");
             mn = (ManagerRemote) ic.lookup("Manager/ManagerBean/remote");
             out.print("Manager obteined<BR>");
            
             out.print("Salvando...<BR>");
             mn.save();
             out.print("Cadastro salvo com sucesso!<BR><BR>");
             out.print("Pesquisando...<BR><BR>");
            
             out.print("<BR><BR>"+mn.getById(1)+"<BR><BR>");
            
            
             } catch(Exception e){
             out.println("ERRO <BR>");
             out.println(e.getMessage());
             }
             %>
             </body>
            </html>
            


            ManagerBean:
            
            package org.classes;
            
            import javax.ejb.Stateful;
            import javax.persistence.EntityManager;
            import javax.persistence.PersistenceContext;
            import org.interfaces.*;
            
            @Stateful
            public class ManagerBean implements ManagerLocal,ManagerRemote{
            
             //## Atributes
             @PersistenceContext(unitName="MyPostgresDS")
             private EntityManager em;
            
             //##Methods
             //##-----------------------------------------------------------------
             public ManagerBean() {
             }
             //##-----------------------------------------------------------------
             public void save(){
             Cadastro cd = new Cadastro();
             cd.setId(1);
             cd.setNome("Marcelo");
            
             em.getTransaction().begin();
             em.persist(cd);
             em.getTransaction().commit();
             }
             //##-----------------------------------------------------------------
             public String getById(int id){
             em.getTransaction().begin(); //is it really necessary?
             Cadastro found = em.find(Cadastro.class,id);
             em.getTransaction().commit(); //is it really necessary?
            
             return(found.getNome());
             }
             //##-----------------------------------------------------------------
            }
            


            Entity:
            
            package org.classes;
            
            import java.io.Serializable;
            import javax.persistence.Column;
            import javax.persistence.Entity;
            import javax.persistence.Id;
            import javax.persistence.Table;
            
            
            @Entity
            @Table(name="cadastro")
            public class Cadastro implements Serializable{
            
             //## Atributes
             private Integer id;
             private String nome;
            
             //##Methods
             //##-----------------------------------------------------------------
             public Cadastro() {
             }
             //##-----------------------------------------------------------------
             @Id
             @Column(name="id")
             public Integer getId() {
             return id;
             }
             //##-----------------------------------------------------------------
             @Column(name="Nome")
             public String getNome() {
             return nome;
             }
             //##-----------------------------------------------------------------
             public void setNome(String nome) {
             this.nome = nome;
             }
             //##-----------------------------------------------------------------
             public void setId(Integer id) {
             this.id = id;
             }
             //##-----------------------------------------------------------------
            }
            


            persistence.xml
            <?xml version="1.0" encoding="UTF-8"?>
            
            <persistence>
             <persistence-unit name="myunit">
             <jta-data-source>java:MyPostgreDS</jta-data-source>
             <class>org.classes.Cadastro</class>
             <properties>
             <propertie name="org.hibernate.hdm2ddl" value="create-table">
             </properties>
             </persistence-unit>
            </persistence>
            


            Data Source: (also added to postgres-ds.xml on jboss deploy folder)
            <datasources>
             <local-tx-datasource>
             <jndi-name>MyPostgreDS</jndi-name>
             <connection-url>jdbc:postgresql://192.168.0.200:5432/netejb</connection-url>
             <driver-class>org.postgresql.Driver</driver-class>
             <user-name>postgres</user-name>
             <password>postgres</password>
             </local-tx-datasource>
            </datasources>
            


            Now i'm getting the following error:

            Manager not bound

            It happens when i try to instance my ManagerBean (remote) in jsp file.

            Am i at the right way now?
            i apologize about my noob skills >.<
            Thank you!