Spring整合hibernate4时出现no session错误

首先将eclipse抛出的错误贴出来:

 严重: Servlet.service() for servlet [springDispatcherServlet] in context with path [/VideoMngSys] threw exception 

[Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread] 

with root cause
org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988)
    at com.vincent.videosys.dao.BaseDao.getSession(BaseDao.java:17)
    at com.vincent.videosys.dao.UserDao.usernameExist(UserDao.java:29)
    at com.vincent.videosys.service.UserService.usernameExistService(UserService.java:19)
    at com.vincent.videosys.controller.home.UserController.usernameExist(UserController.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
    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:748)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal

(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle

(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
....

项目工程结构如下:

下面依次贴出我的相关文件代码:
1.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"
    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">

    <!-- 加载Spring配置文件,Spring应用上下文,理解层次化的ApplicationContext -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

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

    <!-- 可以将POST请求转为PUT请求和DELETE请求 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

2.spring-mvc.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    ......>

    <!-- 向Spring容器注册AutowiredAnnotationBeanPostProcessor、
                     CommonAnnotationBeanPostProcessor、
                     PersistenceAnnotationBeanPostProcessor、
                     RequiredAnnotationBeanPostProcessor,使系统能识别注解 -->
    <context:annotation-config />

    <!-- 使用annotation自动注册bean,并检查@Controller、@Service、@Repository -->
    <context:component-scan base-package="com.vincent.videosys"></context:component-scan>

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置C3P0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>

    <!-- 配置SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <property name="packagesToScan">
            <list>
                <value>com.vincent.videosys.*</value>
            </list>
        </property>
    </bean>

    <!-- 配置hibernate的事务管理器 -->
    <bean id="transactionManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 定义AutoWired自动注入bean -->
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>

    <!-- 用注解来实现事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>    

    <!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.vincent.videosys.service.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config> 
</beans>

4.hibernate.cfg.xml

 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->

        <!-- JDBC connection pool (use the built-in) -->
        <!-- <property name="connection.pool_size">1</property>-->

        <!-- 数据库使用的方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <!-- 设置 打印输出 sql 语句 为真 -->
        <property name="hibernate.show_sql">true</property>

        <!-- 设置格式为 sql -->
        <property name="hibernate.format_sql">true</property>

        <!-- 第一次加载 hibernate 时根据实体类自动建立表结构,以后自动更新表结构 -->
        <property name="hibernate.hbm2ddl.auto">update</property>         

        <property 

name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>

    </session-factory>

</hibernate-configuration>

5.db.properties

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/videomngsys

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

  1. BaseDao.java
 package com.vincent.videosys.dao;

import javax.annotation.Resource;
.....

@Repository("baseDao")
public class BaseDao{

    @Autowired
    protected SessionFactory sessionFactory;

    public Session getSession(){
        return this.sessionFactory.getCurrentSession();
    }

}

7.UserDao.java

 package com.vincent.videosys.dao;

import org.hibernate.Query;
import org.hibernate.Session;
....

@Repository("userDao")
public class UserDao extends BaseDao{

    protected SessionFactory sessionFactory;    

    /**
     * 查看该用户名在数据库中是否存在
     * 存在返回true
     * 不存在返回false
     * 默认返回true
     * @param username
     * @return
     */
    public boolean usernameExist(String username){
        boolean exist = true;

        String hqlString = "from user where username = :username";
        Session session = super.getSession(); 
        Query query = session.createQuery(hqlString);
        query.setParameter("username", username);
        List<User> list = query.list();
        if(list.size() > 0) {
            exist = false;
        }

        return exist;
    }
}

8 UserService.java

 package com.vincent.videosys.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
...

@Transactional
@Service("userService")
public class UserService {

    @Autowired
    private UserDao userDao;

    public boolean usernameExistService(String username){
        return userDao.usernameExist(username);
    }
}
  1. UserController.java
 package com.vincent.videosys.controller.home;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
.....


@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value="/usernameExist",method=RequestMethod.POST)
    public Map<String, String> usernameExist(@RequestParam("username")String usernameString
            ){
        Map<String, String> resultMap = new HashMap<String, String>();
        System.out.println("username: "+usernameString);
        if(userService.usernameExistService(usernameString)){
            resultMap.put("status", "1");//exits
        }
        else{
            resultMap.put("status", "0");//not exist
        }
        return resultMap;
    }

}

每次程序执行到UserController类中的userNameExist方法时,开始调用userService中的方法时,便开始抛出错误.....

2个回答

加上这段配置试试

tx:attributes





/tx:attributes
/tx:advice

 <tx:advice id="txAdvice" transaction-manager="txManager"> 
<tx:attributes> 
<tx:method name="save*" propagation="REQUIRED"/> 
<tx:method name="add*" propagation="REQUIRED"/> 
<tx:method name="create*" propagation="REQUIRED"/> 
<tx:method name="insert*" propagation="REQUIRED"/> 
<tx:method name="*" read-only="true" /> 
</tx:attributes> 
</tx:advice> 
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!