Foros del Web » Programación para mayores de 30 ;) » Java »

Error en Java Netbeans Hibernate, NullPointerException

Estas en el tema de Error en Java Netbeans Hibernate, NullPointerException en el foro de Java en Foros del Web. Estimados: Soy nuevo en el foro y tengo una duda que me ha tenido estancado hace algunos días. Debo realizar una aplicación de escritorio que ...
  #1 (permalink)  
Antiguo 23/11/2015, 13:03
 
Fecha de Ingreso: noviembre-2015
Mensajes: 4
Antigüedad: 8 años, 5 meses
Puntos: 0
Pregunta Error en Java Netbeans Hibernate, NullPointerException

Estimados:

Soy nuevo en el foro y tengo una duda que me ha tenido estancado hace algunos días.

Debo realizar una aplicación de escritorio que descargue unos archivos (.xls) desde una pagina en donde se exige registro. Existía una aplicacion en Java que ya funcionaba, y he seguido la linea de dicha app. Esta trabaja con Hibernate, pero hay unos errores que aun no logro resolver. Este es el log de excepciones:

Cita:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Negocio.NegClaves.<init>(NegClaves.java:21)
at Control.ControlUEN.<init>(ControlUEN.java:9)
at Vista.Principal.btnIniciarActionPerformed(Principa l.java:204)
at Vista.Principal.access$000(Principal.java:18)
at Vista.Principal$1.actionPerformed(Principal.java:5 8)
at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.jav a:6516)
at javax.swing.JComponent.processMouseEvent(JComponen t.java:3321)
at java.awt.Component.processEvent(Component.java:628 1)
at java.awt.Container.processEvent(Container.java:222 9)
at java.awt.Component.dispatchEventImpl(Component.jav a:4872)
at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
at java.awt.Component.dispatchEvent(Component.java:46 98)
at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719 )
at java.awt.Component.dispatchEvent(Component.java:46 98)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:747)
at java.awt.EventQueue.access$300(EventQueue.java:103 )
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:720)
at java.awt.EventQueue$4.run(EventQueue.java:718)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java: 717)
at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:91)

Codigo HibernateUtil:


Código:
import java.io.File;
import java.io.PrintStream;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

public class NegHibernateUtil {

    private static SessionFactory sessionFactory = buildSessionFactory();
    
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            
            //return new Configuration().configure().buildSessionFactory();
            
            sessionFactory = new Configuration().configure().buildSessionFactory();
            
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        return null;
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
NegClaves:

Código:
import Entidades.ClavesRl;
import static Negocio.NegHibernateUtil.getSessionFactory;
import static java.sql.DriverManager.println;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


public class NegClaves {
    
     Session sesion;
  
  public NegClaves(){
    
    //this.sesion = (Session) getSessionFactory();
    this.sesion = NegHibernateUtil.getSessionFactory().openSession();
  }
  
  public String clave(String UEN){
    Query q;
    q = this.sesion.createQuery("from ClavesRl where UEN='" + UEN + "'");
    List<ClavesRl> clave = q.list();
    String retorno = ((ClavesRl)clave.get(0)).getPass();
    
    return retorno;
  }
  
  public ClavesRl todo(String UEN){
    Query q; 
    q = this.sesion.createQuery("from ClavesRl where UEN='" + UEN + "'");
    List<ClavesRl> clave = q.list();
    ClavesRl retorno = (ClavesRl)clave.get(0);
    
    return retorno;
  }
  
  public boolean uppClave(ClavesRl p)
    throws Exception
  {
    this.sesion.clear();
    Transaction tx = this.sesion.beginTransaction();
    this.sesion.saveOrUpdate(p);
    tx.commit();
    return true;
  }
Favor ayuda!
  #2 (permalink)  
Antiguo 23/11/2015, 13:24
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Error en Java Netbeans Hibernate, NullPointerException

Buenas,

El error esta en la linea 21 de la clase NegClaves. Estas intentando acceder a un metodo o propiedad de un objeto cuyo valor es null.


Un saludo
__________________
If to err is human, then programmers are the most human of us
  #3 (permalink)  
Antiguo 23/11/2015, 13:41
 
Fecha de Ingreso: noviembre-2015
Mensajes: 4
Antigüedad: 8 años, 5 meses
Puntos: 0
Respuesta: Error en Java Netbeans Hibernate, NullPointerException

Buenas,

Si lo se que el error está ahí, quisiera saber si la sintaxis de esa línea esta bien, o que habría que cambiarle al código.

Saludos
  #4 (permalink)  
Antiguo 23/11/2015, 13:50
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Error en Java Netbeans Hibernate, NullPointerException

Buenas,

Y si sabes que esta ahi, porque no pones esa linea en concreto? No tiene sentido que nos pongamos los demas a contar las lineas de tu codigo no?

El error no tiene nada que ver con la sintaxis. No es un error de compilacion sino de ejecucion. Posiblemente alguno de tus metodos get() o list() no devuelven ningun resultado para la consulta y en tu codigo nunca lo compruebas.

Por ejemplo (no se si es ahi donde te da el error), en lugar de hacer
Código Java:
Ver original
  1. ((ClavesRl)clave.get(0)).getPass();

Tendrias que comprobar primero:
Código Java:
Ver original
  1. if (clave.get(0) != null) {
  2. //Recupero el valor

Un saludo
__________________
If to err is human, then programmers are the most human of us
  #5 (permalink)  
Antiguo 23/11/2015, 14:00
 
Fecha de Ingreso: noviembre-2015
Mensajes: 4
Antigüedad: 8 años, 5 meses
Puntos: 0
Respuesta: Error en Java Netbeans Hibernate, NullPointerException

El error segun Netbeans es en esta linea de codigo:

Código:
this.sesion = NegHibernateUtil.getSessionFactory().openSession();
esto quiere decir que el método getSessionFactory() esta devolviendo null cierto (?). Este código es creado automáticamente por la misma librería Hibernate, por eso desconozco que puede ser lo que esta impidiendo la ejecución.


Saludos!! Ojalá pueda ayudarme.
  #6 (permalink)  
Antiguo 24/11/2015, 02:36
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Error en Java Netbeans Hibernate, NullPointerException

Eso te pasa porque en este metodo:

Código Java:
Ver original
  1. private static SessionFactory buildSessionFactory() {
  2.         try {
  3.             // Create the SessionFactory from standard (hibernate.cfg.xml)
  4.             // config file.
  5.            
  6.             //return new Configuration().configure().buildSessionFactory();
  7.            
  8.             sessionFactory = new Configuration().configure().buildSessionFactory();
  9.            
  10.         } catch (Throwable ex) {
  11.             // Log the exception.
  12.             System.err.println("Initial SessionFactory creation failed." + ex);
  13.             throw new ExceptionInInitializerError(ex);
  14.         }
  15.         return null;
  16.     }

Estas devolviendo SIEMPRE null en lugar del factory.

Un saludo
__________________
If to err is human, then programmers are the most human of us
  #7 (permalink)  
Antiguo 24/11/2015, 07:12
 
Fecha de Ingreso: noviembre-2015
Mensajes: 4
Antigüedad: 8 años, 5 meses
Puntos: 0
Respuesta: Error en Java Netbeans Hibernate, NullPointerException

Tienes razón, no lo había notado la verdad, veré como me va al modificar el código.


Saludos.

Etiquetas: hibernate, netbeans, sql, string
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 04:17.