bean ไม่เดินสายอัตโนมัติในการรวม mvc ไฮเบอร์เนตและสปริง?

ฉันยังใหม่กับ Spring และกำลังสร้างหน้าเข้าสู่ระบบโดยใช้ Spring และ Hibernate แต่ในขณะที่รับ sessionFactory มันทำให้ฉันมีข้อผิดพลาดนี้ -

Spring: ไม่มีเซสชัน Hibernate เชื่อมโยงกับเธรด และการกำหนดค่าไม่อนุญาตให้สร้างเซสชันที่ไม่ใช่ธุรกรรมที่นี่

ฉันกำลังดิ้นรนจาก 1 วัน ฉันจะแก้ไขมันได้อย่างไร. รหัสของฉันคือ -

UserDao -

package com.mogae.springLogin.db.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.hibernate.SessionFactory;

import com.mogae.springLogin.entities.User;

public class UserDao {

    private static Logger LOGGER = Logger.getLogger(UserDao.class.getName());
    private SessionFactory sessionFactory;



    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

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

    @SuppressWarnings("unchecked")
    public User findUser(String username,String password)
    {
        List<User> users = new ArrayList<User>();
        try{
    //      LOGGER.info("session = "+getFactory().getCurrentSession().isOpen());
        LOGGER.info("login for username = "+username);
        users = getSessionFactory().getCurrentSession().createQuery("from user_data where username =? and password = ?").setParameter(0, username).setParameter(1, password).list();
        }catch(Exception e){
            e.printStackTrace();
        }

        if(users.size()>0)
            return users.get(0);
        else
            return null;
    }

}

คลาสคอนโทรลเลอร์คือ -

package com.mogae.springLogin.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.mogae.springLogin.db.dao.UserDao;
import com.mogae.springLogin.entities.User;

@Controller
@RequestMapping("/login")
public class LoginController {

@Autowired
private UserDao userDao;


    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView loginUser(@RequestParam("username") String username,
            @RequestParam("password") String password) {
        User user = userDao.findUser(username, password);
        if (user != null)
            return new ModelAndView("jsp/result", "message",
                    "successfully login with user = " + username);
        else
            return new ModelAndView("jsp/index", "message",
                    "invalid login");
    }

}

applicationContext.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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"></property>
        <property name="url" value="jdbc:postgresql://localhost:5432/testdb"></property>
        <property name="username" value="postgres"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>

        <property name="mappingResources">
            <list>
                <value>user.hbm.xml</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>


    <bean id="userDao" class="com.mogae.springLogin.db.dao.UserDao">
         <property name="sessionFactory" ref="mySessionFactory"></property>
    </bean>


</beans>  

spring-servlet.xml คือ-

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.0.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

<context:component-scan base-package="com.mogae.springLogin.controllers" />

<!-- Configuration defining views files -->

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

web.xml ของฉันคือ -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>springLogin</display-name>
    <welcome-file-list>
        <welcome-file>jsp/index.jsp</welcome-file>
    </welcome-file-list>
    <!-- Spring Configuration -->
        <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
     <context-param>
        <param-name>log4jXMLpath</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml, /WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>
</web-app>

Stack-Trace ของฉันคือ -

2015-01-18 18:22:57,346 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] Opening Hiber
nate Session
2015-01-18 18:22:57,836 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] Closing Hiber
nate Session
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not a
llow creation of non-transactional one here
        at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionConte
xt.java:63)
        at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:574)
        at com.mogae.springLogin.db.dao.UserDao.findUser(UserDao.java:35)
        at com.mogae.springLogin.controllers.LoginController.loginUser(LoginController.java:24)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(Handl
erMethodInvoker.java:710)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(
HandlerMethodInvoker.java:167)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandl
erMethod(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(Anno
tationMethodHandlerAdapter.java:402)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647
)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.j
ava:305)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)

        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987
)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.jav
a:539)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
2015-01-18 18:22:58,166 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory]
 Invoking afterPropertiesSet() on bean with name 'jsp/index'
2015-01-18 18:22:58,169 DEBUG [org.springframework.web.servlet.DispatcherServlet] Rendering view [or
g.springframework.web.servlet.view.JstlView: name 'jsp/index'; URL [/jsp/index.jsp]] in DispatcherSe
rvlet with name 'spring'
2015-01-18 18:22:58,170 DEBUG [org.springframework.web.servlet.view.JstlView] Added model object 'me
ssage' of type [java.lang.String] to request in view with name 'jsp/index'
2015-01-18 18:22:58,186 DEBUG [org.springframework.web.servlet.view.JstlView] Forwarding to resource
 [/jsp/index.jsp] in InternalResourceView 'jsp/index'
2015-01-18 18:22:58,215 DEBUG [org.springframework.web.servlet.DispatcherServlet] Successfully compl
eted request

person Amit Das    schedule 18.01.2015    source แหล่งที่มา
comment
ดู stackoverflow.com/a/3652125/870248 และ stackoverflow.com/a/11709272/870248   -  person Paul Vargas    schedule 18.01.2015
comment
@PaulVargas ฉันตรวจสอบว่าตอนนี้ฉันกำลังใช้ applicationContext.xml ใน conext-param ใน web.xml แต่ตอนนี้มีข้อผิดพลาดใหม่เกิดขึ้นในรหัสเดียวกันของฉัน เซสชันไฮเบอร์เนตเชื่อมโยงกับเธรดและการกำหนดค่าไม่อนุญาตให้สร้าง   -  person Amit Das    schedule 18.01.2015
comment
โพสต์การติดตามสแต็กจริงหรือไม่   -  person ConMan    schedule 18.01.2015
comment
ลองเพิ่มคุณสมบัตินี้ในการกำหนดค่าไฮเบอร์เนตของคุณด้วย: ‹property name=current_session_context_class›org.hibernate.context.ThreadLocalSessionContext‹/property›   -  person ConMan    schedule 18.01.2015
comment
@ConMan ในการเพิ่มคุณสมบัติแสดงว่าไม่ใช่วิธี setter ที่ถูกต้อง ....   -  person Amit Das    schedule 18.01.2015
comment
ข้อใดไม่ใช่วิธี setter ที่ถูกต้อง คุณต้องให้บางอย่างที่เป็นเรื่องจริงแก่ฉัน ไม่ใช่การตีความของคุณ คุณสามารถโพสต์การติดตามสแต็กได้หรือไม่?   -  person ConMan    schedule 18.01.2015
comment
@ConMan ฉันได้เพิ่มการติดตามสแต็กในคำถาม ... ตรวจสอบว่าสำหรับคุณสมบัตินี้มันบอกว่าสำหรับสิ่งนี้ ไม่พบตัวตั้งค่าที่ถูกต้อง - ‹property name=current_session_context_class›org.hibernate.context.ThreadLocalSessionCon‌​text‹/property›   -  person Amit Das    schedule 18.01.2015
comment
คุณต้องมีธุรกรรมเพื่อใช้ Hibernate อ่านเอกสารประกอบเกี่ยวกับธุรกรรมในเอกสาร Spring: docs .spring.io/spring/docs/current/spring-framework-reference/   -  person JB Nizet    schedule 18.01.2015
comment
ฉันคิดว่าคุณต้องเชื่อมต่ออัตโนมัติ: sessionFactory ส่วนตัว sessionFactory; ใน UserDao   -  person Abhi    schedule 18.01.2015


คำตอบ (1)


เท่าที่ฉันรู้ Spring มองหาอินเทอร์เฟซสำหรับ Autowired beans ดังนั้นฉันคิดว่าคุณต้องประกาศอินเทอร์เฟซสำหรับคลาส userDao ของคุณและในการนำไปใช้งาน คุณใส่คำอธิบายประกอบนี้ @Repository("userDao") เช่นนี้

public interface UserDao {
   .......
}

@Repository("userDao")
public class UserDaoImpl implements UserDao {
 ........
}
person Billydan    schedule 18.01.2015
comment
แต่ฉันต้องการมันโดยไม่ต้องใช้อินเทอร์เฟซใดๆ - person Amit Das; 18.01.2015
comment
ฉันจะช่วยคุณได้ stackoverflow.com/ คำถาม/6511276/ stackoverflow.com/questions /2387431/ - person Billydan; 18.01.2015