java.lang.Nullpointerexception error

Asked

Viewed 15 times

0

Good, I’m trying to use Session = sessionFactory.openSession(); to fetch objects in the BD and give me the following error.

Exception in thread "main" java.lang.Nullpointerexception at org.ual.aas.lab01.controllers.DAO.getSession(DAO.java:18) at org.ual.aas.lab01.controllers.Tasklistcontroller.getLists(Tasklistcontroller.java:17) at org.ual.aas.lab01.controllers.Persistencecontroller.main(Persistencecontroller.java:96) underlined text

 public static Session getSession() {
            Session session = (Session) DAO.session.get();

            if (session == null) {
                session = sessionFactory.openSession();
                DAO.session.set(session);
            }

            return session;
        }

        protected void begin() {
            getSession().beginTransaction();
        }

        protected void commit() {
            getSession().getTransaction().commit();
        }

        protected void rollback() {
            try {
                getSession().getTransaction().rollback();
            } catch( HibernateException e ) {
                System.out.println("Não foi possível fazer rollback da transação");
            }

            try {
                getSession().close();
            } catch( HibernateException e ) {
                System.out.println("Não foi possível fazer fechar a sessão");
            }

            DAO.session.set(null);
        }

        public static void close() {
            getSession().close();
            DAO.session.set(null);
        }


        private static final ThreadLocal session = new ThreadLocal();

        static final SessionFactory sessionFactory = null;
            final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
             .configure("resource/hibernate.cfg.xml")
             .build();
}
//Gera lista de listas
    public static TaskList  getLists(TaskList List)  {  

        DAO.getSession().beginTransaction();
        List resultado = DAO.getSession().createQuery("from TaskList").list();

        for(TaskList list : (List<TaskList>)resultado) {
             System.out.println(list.getName());        
        System.out.println(List.getName());
        }

        return null;
  • You are setting null in various places of your code.

  • Try not to use null in your code. I notice that you do DAO.session.set(null); but I haven’t found anywhere where you put the value on this Object. So clearly Nullpointexception is going to happen. Another suggestion is not to use an object of yours to manage the session, you call it DAO. Better to use your own getSession() that you have.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.