如何从spring-dispatcher-servlet.xml访问SessionFactory到DAO

时间:2017-01-01 11:51:37

标签: java spring hibernate spring-mvc

我在hibernate的帮助下创建了一个spring web应用程序。我为所有配置创建了spring-dipatcher-servlet.xml。我想使用hibernate访问数据库而不创建hibernate.cfg.xml文件,因为我正在使用spring。我在访问DAO中的会话工厂时遇到空指针异常。

以下是我到目前为止所做的工作的片段。

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

     <context:component-scan base-package="com.quiz_mcq.controller" /> 

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/quiz_mcq" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>  
        <property name="packagesToScan" value="com.quiz_mcq.bean"></property>
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.show_sql">true</prop>  
            </props>  
        </property>  

    </bean>  



    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/" />
      <property name="suffix" value=".jsp" />
    </bean>


</beans>

---弹簧调度员的servlet ---

@Controller
public class QuizMcqController {

    UserService userService;

    @RequestMapping(value="/welcome.htm")
    public ModelAndView redirectToLoginPage(){

        ModelAndView modelAndView = new ModelAndView("login");
        return modelAndView;

    }

    @RequestMapping(value="/AuthenticateUser.htm", method = RequestMethod.POST)
    public ModelAndView authenticateUser(@RequestParam("username") String username, @RequestParam("password")String password){

        userService = new UserService();
        boolean flag  = userService.authenticate(username,password);
        if(flag){
            ModelAndView modelAndView = new ModelAndView("login");
            return modelAndView;
        }
        else{
            ModelAndView modelAndView = new ModelAndView("wrong");
            return modelAndView;
        }


    }


}

---控制器---

public class UserService {

    User user;
    UserDao dao;

    public boolean authenticate(String username, String password) {
        user = new User();
        user.setUsername(username);
        user.setPassword(password.toCharArray());

        if(dao.authenticateUser(user))
        {
            return true;
        }

        return false;

    }
}

---服务---

@Repository
public class UserDao implements IUser {

    @Autowired
    SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

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

    @Override
    public boolean authenticateUser(User user) {
        String username = user.getUsername();
        char[] password = user.getPassword();
        System.out.println(username +" <----> "+password);
        String hql = "from User where username='username' and password ='password'";
        Query query = getSessionFactory().openSession().createQuery(hql);
        List list = new ArrayList();
        list = query.list();
        if (list.size() > 0 && list != null) {
            return true;
        }

        return false;
    }

}

--- DAO ---

vwVertical=[[UIView alloc] init];
[vwVertical setBackgroundColor:[UIColor whiteColor]];
vwVertical.translatesAutoresizingMaskIntoConstraints = NO;
vwVertical.layer.shadowColor=[UIColor colorWithRed:32/255 green:59/255 blue:90/255 alpha:1.0].CGColor;
vwVertical.layer.shadowOffset=CGSizeMake(5, 0);
vwVertical.layer.shadowOpacity=0.12;
vwVertical.layer.shadowRadius=6.5;
[vwBlock addSubview:vwVertical];

我如何解决我的问题,我做错了什么?

提前致谢。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这里的问题是你的调度程序servlet当前不知道如何创建和设置bean SessionFactory。 (如您所见,您的setSessionFactory位于UserDao类中)

您可能需要在UserDao中声明spring-dispatcher-servlet.xml bean。

例如:

<bean id="userDAO" class="your.package.nameforUserDao">
  <property name="sessionFactory" ref="sessionFactory" />
</bean>