spring-Spring整合hibernate4时出现no session错误

问题描述

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中的方法时,便开始抛出错误.....

解决方案

hibernate 错误 org.hibernate.LazyInitializationException: could not initialize proxy - no Session
hibernate错误:could not initialize proxy - no Session
Hibernate3 错误: could not initialize proxy - no Session

解决方案二:

加上这段配置试试

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>
时间: 2024-09-13 11:51:35

spring-Spring整合hibernate4时出现no session错误的相关文章

sessionfactory-Spring整合hibernate4时sessionFactory问题

问题描述 Spring整合hibernate4时sessionFactory问题 org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.QueryTimeoutException: Could not open connection org.spring

Spring3.1整合Hibnerte4.1无法获取session错误,求指教!

问题描述 spring的配置文件<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org

整合服务器时易犯十个错误

  由于企业希望改进IT基础架构节省成本,所以CIO和数据中心管理人员都转向了通过合并服务器的方法以实现节省费用.其实,这么做并非易事.由于企业希望改进IT基础架构节省成本,所以CIO和数据中心管理人员都转向了通过合并服务器的方法以实现节省费用.其实,这么做并非易事. 从财务角度来看,虽然服务器整合很有价值,但是并不意味着这一工程很容易实施.一些错误观念使实现成本控制和构建高效数据中心这一目的变得十分困难. 整合就是购买新硬件 整合并不意味着要购买昂贵的新硬件,与你现有的产品相融合可以节约支出,

spring mvc+spring3+hibernate4的事务不会自动清楚session缓存

问题描述 spring mvc+spring3+hibernate4的事务不会自动清楚session缓存 没有手动清缓存,就不执行插入SQL了手动清缓存的话,就能添加成功. 有知道原因的大神吗!!! 解决方案 没遇到过这种情况,tomcat么 解决方案二: 你这个没有加上事务,save时不会自动flush,加了事务之后commit时会自动flush.你配置事务了吗? 解决方案三: 贴出事务来看看,会不会没起作用

Hibernate+Spring+Struts2整合开发中的一个分页显示方案

分页显示一直是web开发中一大烦琐的难题,传统的网页设计只在一个JSP或 者ASP页面中书写所有关于数据库操作的代码,那样做分页可能简单一点,但当 把网站分层开发后,分页就比较困难了,下面是我做Spring+Hibernate+Struts2 项目时设计的分页代码,与大家分享交流. 1.DAO层接口的设计,在MemberDao接口中定义了如下两个方法: public interface MemberDao{ //省略了其他的代码 /** *//** * 分页查询 * @param hql 查询的

java类的问题哈哈哈哈-hibernate和spring怎么整合的

问题描述 hibernate和spring怎么整合的 hibernate和spring添加切面配置是如何搞得,请各位大神指点我,谢谢啦 解决方案 http://wenku.baidu.com/link?url=JWek_B9UHh9ZkM1l80KvA1nmq6ePWUTq94zbWQVTe_2rL89R-pWdR3y3uBM5m2aRZBcruy2k2jsniuR3CTUtbLeoGbG4UswO6qECEumiFzu 解决方案二: http://blog.163.com/cui_zhouya

Spring hibernate 整合报的错

问题描述 Spring hibernate 整合报的错 SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListenerorg.springframework.beans.factory.BeanCreationException: Error creating bean with name

求解:关于struts1+spring+ibatis整合的问题

问题描述 struts1+spring+ibatis整合,都配置好了,可是老报错说找不到方法struts1的配置<action name="timePlanForm" path="/TimePlan"type="org.springframework.web.struts.DelegatingActionProxy" scope="request"parameter="cmd"><forw

struts2 spring hibernate整合后报错

问题描述 struts2 spring hibernate整合后报错 在eclipse里面run on server之后,可以正确显示界面,但当填写表单点击按钮后出现了这个报错 Struts Problem Report Struts has detected an unhandled exception: Messages: 1.org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session; 2.Method