Hibernate NullPointerException when executing session.close ();

0

Very good, I am using hibernate for the first time and I am trying to make a simple application where I now skip an error that I do not know what it might mean. I followed a series of tutorials in which I explained how to configure everything and so far everything went well, I was able to execute selects, inserts and deletes without problems, but from a moment here I started to give problems with any operation I would like to execute .

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="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="hibernate.connection.url">jdbc:sqlserver://DESKTOP-A1M7E3R:1433;databaseName=Agencia</property>
    <property name="hibernate.connection.username">sa</property>
    <property name="hibernate.connection.password">1234</property>
    <property name="show_sql">true</property>
    <mapping resource="Models/Avion.hbm.xml"/>
    <mapping resource="Models/Sucursal.hbm.xml"/>
    <mapping resource="Models/Vuelo.hbm.xml"/>
    <mapping resource="Models/Cliente.hbm.xml"/>
    <mapping resource="Models/Hotel.hbm.xml"/>
    <mapping resource="Models/Clase.hbm.xml"/>
    <mapping resource="Models/Reservacion.hbm.xml"/>
    <mapping resource="Models/Habitacion.hbm.xml"/>
    <mapping resource="Models/Tipo.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="Agencia"/>
  <table-filter match-name="Habitacion"/>
  <table-filter match-name="Clase"/>
  <table-filter match-name="Reservacion"/>
  <table-filter match-name="Avion"/>
  <table-filter match-name="Tipo"/>
  <table-filter match-name="Hotel"/>
  <table-filter match-name="Sucursal"/>
  <table-filter match-name="Vuelo"/>
  <table-filter match-name="Cliente"/>
</hibernate-reverse-engineering>

ClienteDAO.java

package DAO;

import Models.Cliente;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author GerardoAGL
 */
public class ClienteDAO {

    private Session sesion;
    private Transaction tx;

    public int guardar(Cliente cliente) {
        int id = 0;

        try{
            iniciaOperacion();
            id = (int) sesion.save(cliente);
            tx.commit();
        }catch(HibernateException e){
            manejaExcepcion(e);
        }finally{
            sesion.close();
        }

        return id;
    }

    public List<Cliente> buscar(String busqueda) {

        List<Cliente> clientes = null;
        String sql ="FROM Cliente WHERE "
                + "nombre LIKE '%"+busqueda+"%' OR "
                + "apellido LIKE '%"+busqueda+"%' OR "
                + "cedula LIKE '%"+busqueda+"%'";

        try{
            iniciaOperacion();
            clientes = sesion.createQuery(sql).list();
        }finally{
            sesion.close();
        }

        return clientes;
    }

    public void eliminar(Cliente cliente) {
        try{
            iniciaOperacion();
            sesion.delete(cliente);
            tx.commit();
        }catch(HibernateException e){
            manejaExcepcion(e);
        }finally{
            sesion.close();
        }
    }

    private void iniciaOperacion() throws HibernateException{

        sesion = NewHibernateUtil.getSessionFactory().openSession();
        tx = sesion.beginTransaction();
    }

    private void manejaExcepcion(HibernateException e) throws HibernateException {

        tx.rollback();
        throw new HibernateException("Ocurrió un error en la capa de acceso a datos", e);
    } 
}

This is the error I have

INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect
sep 03, 2017 11:20:03 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
sep 03, 2017 11:20:03 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at DAO.ClienteDAO.guardar(ClienteDAO.java:33)
    at Controllers.CreateClientController.guardarCliente(CreateClientController.java:67)
    at Controllers.CreateClientController.actionPerformed(CreateClientController.java:44)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

The line that causes me the problem, of the ClienteDAO class is the following

Thanks in advance to anyone who can help me.

    
asked by GerardoAGL96 03.09.2017 в 17:28
source

1 answer

2

The problem is that the block finally in Java is going to be executed so throw an exception from catch , as explained in Does the finally block always run in Java? (includes cases where it is not executed). This means that your variable session was not initialized due to some problem and its value is null , therefore when calling session.close() the exception is thrown.

The way to fix your code, by the current design, would be:

//en tus métodos, invocar el siguiente método
finally {
    cerrarSesion(session);
}

//agregar el siguiente método que asegura que no haya problemas
private void cerrarSession(Session session) {
    if (session != null) {
        session.close();
    }
}
    
answered by 03.09.2017 / 17:47
source