Spring3.2+Hibernate4.1集成的时候提示找不到Session

大家好, 我今天在整合spring3+hibernate的时候老是被提示找不到session  我获取session的方式是sessionFactory.getCurrentSession()

控制台报的错误:

严重: Servlet.service() for servlet springmvc threw exception
org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
    at cn.ccsu.dao.impl.UserDaoImpl.getSession(UserDaoImpl.java:48)
    at cn.ccsu.dao.impl.UserDaoImpl.exist(UserDaoImpl.java:22)
    at cn.ccsu.manager.impl.UserManagerImpl.register(UserManagerImpl.java:20)
    at cn.ccsu.web.UserAction.register(UserAction.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:619)

 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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 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.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"
    default-autowire="byName">
    <context:component-scan base-package="cn.ccsu" />
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:config/jdbc.properties</value>
            </list>
        </property>
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="${hibernate.connection.driver_class}" />
        <property name="jdbcUrl" value="${hibernate.connection.url}" />
        <property name="user" value="${hibernate.connection.username}" />
        <property name="password" value="${hibernate.connection.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
            </props>
        </property>

        <property name="packagesToScan">
            <value>cn.ccsu.model</value>
        </property>
    </bean>

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

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


</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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>S3SH</display-name>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        classpath:config/applicationContext.xml
        
        </param-value>
    </context-param>
    <filter>  
        <filter-name>OpenSessionInViewFilter</filter-name>  
        <filter-class>  
                org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
        </filter-class>  
        <!-- 指定在spring配置的sessionFactory -->  
        <init-param>  
            <param-name>sessionFactoryBeanName</param-name>  
            <param-value>mysqlSessionFactory</param-value>  
        </init-param>  
        <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->     
        <init-param>  
                <param-name>singleSession</param-name>  
                <param-value>true</param-value>  
        </init-param>  
     </filter>  
    
    
    

    <!-- 处理中文乱码问题 start -->
    <filter>
        <filter-name>UTF-Encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>

        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>

    </filter>
    <filter-mapping>
        <filter-name>UTF-Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- 处理中文乱码问题 end -->




    <!-- springmvc start -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/springmvc-servlet.xml</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!-- springmvc end -->
</web-app>

 UserManagerImpl.java

package cn.ccsu.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.ccsu.dao.UserDao;
import cn.ccsu.model.UserBean;

@SuppressWarnings("unchecked")
@Component("userDao")
public class UserDaoImpl   implements UserDao {

    @Override
    public boolean exist(UserBean userBean) {
        String hql = "from UserBean userBean where userBean.username=:key";
        Query q = getSession().createQuery(hql);
        q.setParameter("key", userBean.getUsername());
        if (q.list().size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public UserBean addUser(UserBean userBean) {
        getSession().save(userBean);
        return userBean;
    }

    
    @Override
    public List<UserBean> getAllUserList() {
        return getSession().createQuery("from UserBean").list();
    }
    
    
    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;
    
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

}

 以上就是这个项目的主要代码了 请各位大神帮我瞧瞧  多谢

4个回答

org.springframework.orm.hibernate4.SpringSessionContext

注掉试试

huhongyu133
huhongyu133 嗯 我昨天晚上把这个注释掉就OK了, 不过不知道是什么原因。
7 年多之前 回复

在你测试的类上或方法上加@Transactional

huhongyu133
huhongyu133 你好, 我springmvc-servlet.xml文件中改成如下这种了 <context:component-scan base-package="cn.ccsu.web" > <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> 在web这个包里面只有一个UserAction 我在UserManagerImpl 和UserDaoImpl 的类名上都加上了@Transactional注解 运行的时候 还是提示错误,错误如下: org.hibernate.HibernateException: createQuery is not valid without active transaction at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348) at $Proxy22.createQuery(Unknown Source) at cn.ccsu.dao.impl.UserDaoImpl.exist(UserDaoImpl.java:25) …… UserDaoImpl的第25行如下: Query q = getSession().createQuery(hql);
7 年多之前 回复
huhongyu133
huhongyu133 研究ing 多谢
7 年多之前 回复
jinnianshilongnian
jinnianshilongnian 恩 看看我给你发的帖子吧
7 年多之前 回复
huhongyu133
huhongyu133 是springmvc 配置文件中<context:component-scan base-package="cn.ccsu" /> 这个不对吗
7 年多之前 回复
jinnianshilongnian
jinnianshilongnian 在你的web.xml中
7 年多之前 回复
huhongyu133
huhongyu133 1、sessionFactoryBeanName 的value改成sessionFactory sessionFactoryBeanName 我怎么没找到这个东东
7 年多之前 回复
jinnianshilongnian
jinnianshilongnian <context:component-scan base-package="cn.ccsu" /> 不对 请参考[url]http://www.iteye.com/topic/1128522/url]
7 年多之前 回复
huhongyu133
huhongyu133 spirngmvc的配置文件: <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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd"> <context:component-scan base-package="cn.ccsu" /> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/view/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
7 年多之前 回复
jinnianshilongnian
jinnianshilongnian 1、sessionFactoryBeanName 的value改成sessionFactory 2、springmvc的配置文件贴一下
7 年多之前 回复
huhongyu133
huhongyu133 我在UserManagerImpl里面加上了@Transactional @Component("userManager") public class UserManagerImpl implements UserManager { @Override @Transactional public boolean register(UserBean userBean) { if (userDao.exist(userBean)) { return false; } userDao.addUser(userBean); return true; } @Override @Transactional public List<UserBean> getUserList() { return userDao.getAllUserList(); } @Autowired @Qualifier("userDao") private UserDao userDao; }
7 年多之前 回复

org.springframework.orm.hibernate4.SpringSessionContext
改为:
thread
这个试试

huhongyu133
huhongyu133 我给所有的方法都加上了@Transactional
7 年多之前 回复
zhouhua0104
想成为工程师的码农 那是因为使用使用hibernate的getCurrentSession()获得session对象,对查询语句也需要开启事务,不然就会抛出如上异常!
7 年多之前 回复
huhongyu133
huhongyu133 我改成之后<prop key="hibernate.current_session_context_class">thread</prop> 控制台包这个错误: org.hibernate.HibernateException: createQuery is not valid without active transaction
7 年多之前 回复
zhouhua0104
想成为工程师的码农 那你试试<prop key="hibernate.current_session_context_class">thread</prop> 这个吧
7 年多之前 回复
huhongyu133
huhongyu133 我在注解上面添加了@Transactional
7 年多之前 回复
zhouhua0104
想成为工程师的码农 还有一种可能就是你用注解时,没有在service类上添加@Transactional事务控制
7 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐