java.lang.NullPointerException in Hibernate Annotations

0

I'm now watching the annotations part with Hibernate. I show you what I have:

Here is my configuration file called hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
   <property name="connection.driver_class">com.mysql.jdbc.Driver</property>         
        <property name="connection.url">jdbc:mysql://localhost/pruebahibernate</property>     
        <property name="connection.username">hibernate</property>       
        <property name="connection.password">hibernate</property>     
        <property name="connection.pool_size">1</property>         
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>     
        <property name="show_sql">true</property>     
        <property name="hbm2ddl.auto">create-drop</property>      
        <mapping  class="hibernateanotaciones.Contacto" />  
    </session-factory>
</hibernate-configuration>

Here I show you my class - Entity named Contact

package hibernateanotaciones;

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 Jose
 */
@Entity
@Table(name="CONTACTOS")
public class Contacto implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="ID")
    private long id;
    @Column(name="NOMBRE", length = 24)
    private String nombre;
    @Column(name="EMAIL", length = 30)
    private String email;
    @Column(name="TELEFONO", length = 24)
    private String telefono;
public Contacto()
{
}

public Contacto(String nombre, String email, String telefono)
{
    this.nombre = nombre;
    this.email = email;
    this.telefono = telefono;
}

public String getEmail()
{
    return email;
}

public void setEmail(String email)
{
    this.email = email;
}

public long getId()
{
    return id;
}

private void setId(long id)
{
    this.id = id;
}

public String getNombre()
{
    return nombre;
}

public void setNombre(String nombre)
{
    this.nombre = nombre;
}

public String getTelefono()
{
    return telefono;
}

public void setTelefono(String telefono)
{
    this.telefono = telefono;
}
}

I have here my utilitarian class called HibernateUtil that helps me start the SessionFactory

package hibernateanotaciones;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory; 
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil
{  
    private static final SessionFactory sessionFactory;   

    static 
    { 
        try 
        { 
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); 
        } catch (HibernateException he) 
        { 
           System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he); 
            throw new ExceptionInInitializerError(he); 
        } 
    }  

    public static SessionFactory getSessionFactory() 
    { 
        return sessionFactory; 
    } 
    }

Here I have a class called Conexion here is where as such access to my SessionFactory

    package persistencia;

import hibernateanotaciones.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Jose
 */
public class Conexion {
    static Session sesion;
    static Transaction tx;

    public static void iniciaOperacion() throws HibernateException
{
    sesion = HibernateUtil.getSessionFactory().openSession();
    tx = sesion.beginTransaction();
}
    public static void manejaExcepcion(HibernateException he) throws HibernateException
{
    tx.rollback();
    throw new HibernateException("Ocurrió un error en la capa de acceso a datos", he);
}
}

Well here I leave my class persistence called ContactDA

package persistencia;
import hibernateanotaciones.Contacto;
import java.util.List;
import org.hibernate.HibernateException;
public class ContactoDAO {

public long guardarContacto(Contacto contacto)throws HibernateException
{
   long id=0;
   try
   {
       Conexion.iniciaOperacion();
       id=(Long)Conexion.sesion.save(contacto);
       Conexion.tx.commit();
   }catch(HibernateException he)
   {
       Conexion.manejaExcepcion(he);
       throw he;
   }
   finally
   {
       Conexion.sesion.close();
   }
   return id;
}
public void actualizarContacto(Contacto contacto) throws HibernateException
{
    try
    {
        Conexion.iniciaOperacion();
        Conexion.sesion.update(contacto);
        Conexion.tx.commit();
    }catch(HibernateException he)
    {
        Conexion.manejaExcepcion(he);
    }
    finally
    {
        Conexion.sesion.close();
    }
}
public void eliminarContacto(Contacto contacto) throws HibernateException
{
    try
    {
        Conexion.iniciaOperacion();
        Conexion.sesion.delete(contacto);
        Conexion.tx.commit();
    }catch(HibernateException he)
    {
        Conexion.manejaExcepcion(he);
    }
    finally
    {
        Conexion.sesion.close();
    }
}
public Contacto obtenerContacto(long idContacto) throws HibernateException
{
    Contacto contacto=null;
    try
    {
        Conexion.iniciaOperacion();
        contacto=(Contacto)Conexion.sesion.get(Contacto.class, idContacto);
        Conexion.tx.commit();
    }catch(HibernateException he)
    {
        Conexion.manejaExcepcion(he);
    }
    finally
    {
        Conexion.sesion.close();
    }
    return contacto;
}
public List<Contacto> listarContactos() throws HibernateException
{
    List<Contacto> listarContactos=null;
    try
    {
        Conexion.iniciaOperacion();
        listarContactos=Conexion.sesion.createQuery("from Contacto").list();
        Conexion.tx.commit();
    }catch(HibernateException he)
    {
        Conexion.manejaExcepcion(he);
    }
    finally
    {
        Conexion.sesion.close();
    }
    return listarContactos;
}

}

An example of what I do in my MAIN class

import java.util.List;
import persistencia.ContactoDAO;

/**
 * @author Jose
 */
public class HibernateAnotaciones {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        long idConsultar=0;
        Contacto contactoRecuperado=null;

        Contacto contacto1=new Contacto("Maria", "[email protected]", "02122344332");
        Contacto contacto2=new Contacto("Paco", "[email protected]", "02121221332");
        Contacto contacto3=new Contacto("Luis", "[email protected]", "02124432111");

        ContactoDAO contactoDAO=new ContactoDAO();
        idConsultar=contactoDAO.guardarContacto(contacto1);
        contactoDAO.guardarContacto(contacto2);
        contactoDAO.guardarContacto(contacto3);

        contacto2.setNombre("Petrolina");
        contactoDAO.actualizarContacto(contacto2);

        contactoRecuperado=contactoDAO.obtenerContacto(idConsultar);
        System.out.println("El contacto "+contactoRecuperado.getNombre()+" Se ha recuperado");

        contactoDAO.eliminarContacto(contactoRecuperado);

        List<Contacto> listarContacto=contactoDAO.listarContactos();
        System.out.println("Hay "+listarContacto.size()+" Contactos en la base de datos");

        for(Contacto c:listarContacto)
        {
            System.out.println("-> "+c.getNombre());
        }



    }

}

The issue is that when I'm trying to save he says:

    INFO: HHH000206: hibernate.properties not found
Exception in thread "main" java.lang.NullPointerException
  at persistencia.ContactoDAO.guardarContacto(ContactoDAO.java:31)
  at hibernateanotaciones.HibernateAnotaciones.main(HibernateAnotaciones.java:29)
C:\Users\Jose\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

I am following a tutorial to the letter but I do not know what is happening. I'm using:

  • JDBC MYSQL 5.1.4
  • Hibernate 5
  • HibernateAnotation 3.4.0
asked by jose angarita 23.04.2017 в 20:34
source

1 answer

0

For me, the problem is with the IDs, the error is because you are asking for an element that does not exist. Test validating that case.

        if (id > 0) {
        System.out.print(id);
        }else{
        System.out.print("id esta vació!");
        } 
    
answered by 06.06.2017 в 17:09