NPE SessionFactory в интеграции Spring / Hibernate

1

Я новичок в Spring и Hibernate, и у меня есть NPE в этой строке:

Session session = getSessionFactory().getCurrentSession();

Это мой класс UserDAO

public class UserDAO implements IUserDAO{

         private SessionFactory sessionFactory;

          public SessionFactory getSessionFactory() {
              return sessionFactory;
          }
          public void setSessionFactory(SessionFactory sessionFactory) {
              this.sessionFactory = sessionFactory;
          }

        @Override
        public Integer updateUser(User user) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public User searchUserIfExists(String username, String password) {
            Session session = getSessionFactory().getCurrentSession();

            Query query = session.createQuery(SEARCH_USER_ACCT);
            query.setParameter("username", username);
            query.setParameter("password",password);
            List<User> userList = query.list();

            System.out.println(userList.size());
            User user = null;
            return user;
        }

И это мой UserController

@SessionAttributes(value = {"userSession"})
@Controller
public class UserController {

    private IUserDAO userDAO;  

    @Autowired  
    public UserController(IUserDAO userDAO) {  
        this.userDAO = userDAO;  
    }  

    @RequestMapping(value = "/processLogin.htm", method=RequestMethod.POST)
    public String login(@ModelAttribute User user,@RequestParam("username") String username,
              @RequestParam("password") String password,
              HttpServletRequest request, HttpServletResponse response){

        userDAO = new UserDAO();
        User userOb = userDAO.searchUserIfExists(username, password);

        if(userOb != null){
            ModelAndView modelAndView = new ModelAndView();
            String role = userOb.getUserRole();
            switch(role){
                case "admin":   
                    modelAndView.addObject("userSession", userOb);
                    modelAndView.addObject("userId", userOb.getUserId());
                    modelAndView.setViewName("/adminPage_admin");
                    break;
                case "customer":
                    modelAndView.addObject("userSession", userOb);
                    modelAndView.addObject("userId", userOb.getUserId());
                    modelAndView.setViewName("/customerpage_customer");
                    break;

        }



    }
        return "";
    }
}

Это моя конфигурация xml для весны

<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

  <!-- Enable @Controller annotation support -->
 <mvc:annotation-driven />
 <mvc:default-servlet-handler/>
  <!-- Map simple view name such as "test" into /WEB-INF/test.jsp -->
  <beans:bean   class="org.springframework.web.servlet.view.InternalResourceViewResolver">      
        <beans:property name="prefix" value="/jsp" />       
        <beans:property name="suffix" value=".jsp" />   
  </beans:bean>

  <!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->

    <context:component-scan base-package="com.nacv2.*"/>


     <context:spring-configured/>

  <!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with 
       username root and blank password. Change below if it not the case -->
  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/db_nac"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
    <property name="validationQuery" value="SELECT 1"/>
  </bean>

  <!-- Hibernate Session Factory -->
  <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="packagesToScan">

      <array>
        <value>com.nacv2.model.*</value>
      </array>
    </property>
    <property name="hibernateProperties">
      <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
      </props>

    </property>
  </bean>

    <bean id="userDAO" class="com.nacv2.dataaccess.UserDAO">  
            <property name="sessionFactory" ref="mySessionFactory"/>  
    </bean>

  <!-- Hibernate Transaction Manager -->
   <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="mySessionFactory"/>
  </bean>   

  <!-- Activates annotation based transaction management -->

   <tx:annotation-driven transaction-manager="transactionManager"/> 


</beans>    
  • 0
    где вы инициализировали (установили) SessionFactory ???
  • 0
    Это в моем весеннем файле конфигурации xml
Показать ещё 2 комментария
Теги:
spring
spring-mvc
hibernate

1 ответ

3
Лучший ответ

Ваша проблема на самом деле в этой строке:

userDAO = new UserDAO();

Вы правильно подключили Spring и Hibernate, но затем вы идете и создаете новый объект вне их знаний, который не будет знать о вложенных зависимостях. Просто используйте тот, который уже был автоуправлен для вас.

  • 0
    Я понимаю, но как я могу внедрить userDAO в мой контроллер и возможно ли не использовать @Autowired, потому что я не хочу, чтобы мое приложение было связано в Spring?
  • 0
    @ Эрика, это не имеет смысла
Показать ещё 6 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню