0

I am trying use Hibernate for Db access in my Spring app. After some problems with dependencies (now solved), I can run my project normally, and the first page of it open to me (it's a login page). But, when I submit the form to server (this requisition is handled by a spring controller), I receive the follow error message:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause

java.lang.NullPointerException
    org.ligadesportiva.resources.HibernateConfig.restDataSource(HibernateConfig.java:38)
    org.ligadesportiva.resources.HibernateConfig.sessionFactory(HibernateConfig.java:28)
    org.ligadesportiva.data.UsuarioHome.<init>(UsuarioHome.java:31)
    org.ligadesportiva.controller.controller.login(controller.java:36)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

This is the method from controller which handle the requisition:

@RequestMapping(value="/login", method=RequestMethod.POST)
    public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password) throws NoSuchAlgorithmException
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
        byte[] digest = md.digest();

        Usuario temp = new Usuario(username, convertByteToHex(digest));
        UsuarioHome tempHome = new UsuarioHome();
        List<Usuario> lista = tempHome.findByExample(temp);
        if(lista.size() == 0) {
            ModelAndView mav = new ModelAndView();
            mav.setViewName("usuario_login");
            mav.addObject("message", "N&atilde;o foi possivel efetuar o login");
            return mav;
        }
        else {
            this.sessao = new Sessao();
            ModelAndView mav = new ModelAndView();
            mav.setViewName("usuario_start");
            mav.addObject("usuario", temp);
            return mav;
        }
    }

This is my class HibernateConfig:

package org.ligadesportiva.resources;

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:database.properties" })
@ComponentScan({ "org.ligadesportiva.data" })
public class HibernateConfig {

   @Autowired
   private Environment env;

   @Bean
   public AnnotationSessionFactoryBean sessionFactory() {
      AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(new String[] { "org.ligadesportiva.core" });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      BasicDataSource dataSource = new BasicDataSource();
      dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
      dataSource.setUrl(env.getProperty("jdbc.url"));
      dataSource.setUsername(env.getProperty("jdbc.user"));
      dataSource.setPassword(env.getProperty("jdbc.pass"));

      return dataSource;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory().getObject());

      return txManager;
   }

   @SuppressWarnings("serial")
   Properties hibernateProperties() {
      return new Properties() {
         {
            setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
            setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
            setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
         }
      };
   }
}

This is my class DAO (UsuarioHome.java):

package org.ligadesportiva.data;

// Generated 15/03/2014 09:34:19 by Hibernate Tools 3.4.0.CR1

import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.ligadesportiva.core.Usuario;

/**
 * Home object for domain model class Usuario.
 * @see org.ligadesportiva.core.Usuario
 * @author Hibernate Tools
 */
public class UsuarioHome {

    private static final Log log = LogFactory.getLog(UsuarioHome.class);

    private HibernateConfig hibernateConfig = new HibernateConfig();

@Autowired
private final SessionFactory sessionFactory = (SessionFactory) hibernateConfig.sessionFactory();

    public void persist(Usuario transientInstance) {
        log.debug("persisting Usuario instance");
        try {
            sessionFactory.getCurrentSession().persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void attachDirty(Usuario instance) {
        log.debug("attaching dirty Usuario instance");
        try {
            sessionFactory.getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Usuario instance) {
        log.debug("attaching clean Usuario instance");
        try {
            sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void delete(Usuario persistentInstance) {
        log.debug("deleting Usuario instance");
        try {
            sessionFactory.getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Usuario merge(Usuario detachedInstance) {
        log.debug("merging Usuario instance");
        try {
            Usuario result = (Usuario) sessionFactory.getCurrentSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Usuario findById(int id) {
        log.debug("getting Usuario instance with id: " + id);
        try {
            Usuario instance = (Usuario) sessionFactory.getCurrentSession()
                    .get("org.ligadesportiva.data.Usuario", id);
            if (instance == null) {
                log.debug("get successful, no instance found");
            } else {
                log.debug("get successful, instance found");
            }
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(Usuario instance) {
        log.debug("finding Usuario instance by example");
        try {
            List results = sessionFactory.getCurrentSession()
                    .createCriteria("org.ligadesportiva.data.Usuario")
                    .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }
}

And this is my *-servlet.xml file, where I declare the HibernateConfig, following instruction from here: http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/Configuration.html.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="org.ligadesportiva.controller" />
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>    

    <context:annotation-config/>
    <bean class="org.ligadesportiva.resources.HibernateConfig"/>
</beans>

Someone can see what the problem with this code?

Kleber Mota
  • 8,521
  • 31
  • 94
  • 188
  • 1
    Hey, please post the stack trace in a code block instead of a picture. :-) – oschlueter Mar 16 '14 at 11:14
  • The stack trace is telling you that org.hibernate.cache.CacheProvider is not found, did you include the libraries properly? – oschlueter Mar 16 '14 at 11:15
  • yep, that's all libs included: http://i.imgur.com/vi6zEqV.png – Kleber Mota Mar 16 '14 at 11:42
  • Kleber Mota: stop posting images, if you want help, then make it easy for them that wants you to help, so post code that can be copyed, instead of posting an image where every one need to type the class names if one try to look for something in order to help you. – Ralph Mar 16 '14 at 12:03
  • see: http://stackoverflow.com/questions/7528862/exception-noclassdeffounderror-for-cacheprovider – Ralph Mar 16 '14 at 12:05
  • 1
    Didn't read through the question, but I can offer quick observation -> you have problems with your dependencies. I can see mix of Spring 3.2.8 and 4.0.2. That is never a good thing. Also your Hibernate versions seems to not be in sync. – Pavel Horal Mar 16 '14 at 13:09
  • AnnotatedElementsUtils was introduced in Spring 4. You are using Mixed Spring versions. – Bart Mar 16 '14 at 13:12
  • I correct the problem with the versions of Spring and Hibernate, but now I find myself with the error I just update in the question. Seems like this bew problem is related to this method from HiberbateConfig, but I am not sure: **public HibernateTransactionManager transactionManager()** – Kleber Mota Mar 16 '14 at 15:24
  • I finally solve my problem with the dependencies, and now I can reach the initial page from my project. But still have an error (question updated to display the current status of the project) – Kleber Mota Mar 17 '14 at 00:17
  • possible duplicate of [Why is my Spring @Autowired field null?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – chrylis -cautiouslyoptimistic- Mar 17 '14 at 01:15
  • No, that is a complete different question. I don't even using beans until few moments ago (still figuring out how to use, actually). – Kleber Mota Mar 17 '14 at 01:51

1 Answers1

0

The cardinal rule of Spring IoC container is to let Spring manage most, if not all, of your dependencies and objects.

Your HibernateConfig class is annotated with @Configuration. This is an indication that it should be managed by Spring, which you are doing correctly in your context file

<bean class="org.ligadesportiva.resources.HibernateConfig"/>

however, you're not using it anywhere. You're also not declaring a UsuarioHome bean. Instead, you are creating these objects yourself

UsuarioHome tempHome = new UsuarioHome();
// and
private HibernateConfig hibernateConfig = new HibernateConfig();

How do you expect Spring to process them?

Go through the documentation of Spring IoC container to understand how to manage these dependencies through your context configuration.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • I guess this isn't what causing the error. I try configure the class UsuarioHome as a beans, but this way i can't execute the project (in the tradicional the error just is displayd after I submit a form). The same exception happens, and apparently connected to execution of the same method - restDataSource. – Kleber Mota Mar 17 '14 at 00:58
  • @KleberMota This is exactly what is causing the error. You are creating the `HibernateConfig` object yourself as shown above. Because of this the `Environment` field remains `null`. Dereferencing that will throw a `NullPointerException` in `restDataSource()`. – Sotirios Delimanolis Mar 17 '14 at 00:59