簡體   English   中英

Spring MVC - 沒有Hibernate Session綁定到線程

[英]Spring MVC - No Hibernate Session bound to thread

我在hibernate中遇到會話問題:

INFO: Starting ProtocolHandler ["http-bio-8080"]
2013-09-10 16:23:11 org.apache.catalina.startup.Catalina start
 INFO: Server startup in 4000 ms
2013-09-10 16:23:13 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/portal] threw          exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here] with root cause
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
    at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)
    at com.myportal.portal.model.HibernateDao.getSessionFactory(HibernateDao.java:31)
    at com.myportal.portal.model.HibernateDao.testowa(HibernateDao.java:46)
    at com.myportal.portal.controllers.HomeController.home(HomeController.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

我已經閱讀了有關此問題的一些內容,但解決方案在我的案例中不起作用。

我的Dao班:

package com.myportal.portal.model;
import org.hibernate.classic.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.myportal.portal.entity.User;

@Repository
@Transactional(propagation=Propagation.REQUIRED)
public class HibernateDao {
    @Autowired
    private SessionFactory sessionFactory;


    public HibernateDao()
    {

    }
    public HibernateDao(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }
    private Session getSessionFactory()
    {
        return sessionFactory.getCurrentSession();
    }

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

    public void testowa()
    {
        User u = new User();
        //SessionFactory sf = getSessionFactory();
        //Session s = sf.openSession().beginTransaction()

        // problem with this
        Session session = getSessionFactory();
        //session.save(u);

    }
}

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

    <!-- Root Context: defines shared resources visible to all other web components -->


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

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/hibernate1"/>
    <property name="username" value="root2"/>
    <property name="password" value=""/>
    <property name="initialSize" value="5"/>
    <property name="maxActive" value="10"/>
</bean>    

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
   <property name="dataSource" ref="dataSource"/>
   <property name="packagesToScan" value="com.spoleczniak.projekt.model"/>
   <property name="hibernateProperties">
       <props>
           <prop key="dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
           <prop key="show_sql">true</prop>
       </props>
   </property>
</bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

     <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

</beans>

servlet的context.xml中

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
    <context:annotation-config/>
<context:component-scan base-package="com.myportal.portal" />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

我這樣使用它:

@Controller
public class RegisterController {

    @Autowired
    private HibernateDao hibernateDao;

    @RequestMapping(value="/register")
    public String registerForm()
    {
        hibernateDao.testowa();
        return "register";
    }
}

我該如何解決?

我更改DAO並創建UserService,但仍然出現錯誤:

DAO:

@Repository
public class HibernateDao {
    @Autowired
    private SessionFactory sessionFactory;


    public HibernateDao()
    {

    }
    public HibernateDao(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }
    private Session getSessionFactory()
    {
        return sessionFactory.getCurrentSession();
    }

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

    public void testowa()
    {
        User u = new User();
        //SessionFactory sf = getSessionFactory();
        //Session s = sf.openSession().beginTransaction()

        // problem with this
        Session session = getSessionFactory();
        //session.save(u);

    }
} 

UserService:

@Service
public class UserService {

    @Autowired
    private HibernateDao hibernateDao;


    @Transactional
    public void addContact() 
    {
        hibernateDao.testowa(); 
    }
}

控制器:

@Controller
public class RegisterController {

    @Autowired
    private UserService userService;

    @RequestMapping(value="/register")
    public String registerForm()
    {
        userService.addContact();
        return "register";
    }
}

發生了什么事情是你的servlet-context.xml覆蓋了root-context.xml bean,因為它聲明了包含@Repository類的包的component-scan servlet-context.xml ,你有

<context:component-scan base-package="com.myportal.portal" />

而您的HibernateDao類位於com.myportal.portal.model 這個ApplicationContext將創建一個沒有事務管理HibernateDao bean,因為它沒有<tx:annotation-driven> @Controller自動裝配的HibernateDao bean就是這個,而不是root-context.xml (具有事務管理)的那個。

要解決此問題,您首先需要添加

<context:component-scan base-package="com.myportal.portal.model" />

到您的root-context.xml並刪除<context:annotation-config/> (這是多余的)。 然后,您想將servlet-context.xmlcomponent-scan修改為更具體的內容,其中不包含@Repository類的包

<context:component-scan base-package="com.myportal.portal.controllers" />

該軟件包將包含您的@Controller類。 您也不需要<context:annotation-config>

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

這意味着該線程中沒有當前事務。

當您更正我時,該類使用@Transactional進行了注釋,但是我看到它沒有實現接口。 可能發生的情況是,生成的代理不會像在未實現接口的情況下為控制器添加注釋那樣公開注釋。

了解CGLIB代理為什么不保留某些注釋

在bean實例化期間,讀取servlet-context.xml並實例化具有@Controller @Service@Repository @Controller@Service @Repository的bean。

現在,當讀取application-context.xml (具有<tx:annotation-driven /> )時,bean已經存在,因此不會獲得事務行為。 servlet-context.xml的程序包制作為特定於UI的控制器/控制器,或從組件掃描中排除Service Repository程序包。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM