今天在整合SSH的时候,一开始我再测试的时候service层添加了注解事务调用DAO可以正常的保存,在环境中我在XML中采用了spring的OpenSessionInViewFilter解决hibernate的no-session问题(防止页面采用蓝懒加载的对象,此过滤器在访问请求前打开session,访问结束关闭session),xml配置如下:

    <!--Hibernate的session丢失解决方法 -->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

  当我在service层将事务注解注释掉之后报错,代码如下,错误如下:

 错误信息:

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1126)

原因:

上面的错误:

    只读模式下(FlushMode.NEVER/MANUAL)写操作不被允许:把你的Session改成FlushMode.COMMIT/AUTO或者清除事务定义中的readOnly标记。

摘自一位大牛的解释:

OpenSessionInViewFilter在getSession的时候,会把获取回来的session的flush mode 设为FlushMode.NEVER。然后把该sessionFactory绑定到TransactionSynchronizationManager,使request的整个过程都使用同一个session,在请求过后再接除该sessionFactory的绑定,最后closeSessionIfNecessary根据该session是否已和transaction绑定来决定是否关闭session。在这个过程中,若HibernateTemplate 发现自当前session有不是readOnly的transaction,就会获取到FlushMode.AUTO Session,使方法拥有写权限。也即是,如果有不是readOnly的transaction就可以由Flush.NEVER转为Flush.AUTO,拥有insert,update,delete操作权限,如果没有transaction,并且没有另外人为地设flush model的话,则doFilter的整个过程都是Flush.NEVER。所以受transaction(声明式的事务)保护的方法有写权限,没受保护的则没有。

查看OpenSessionInViewFilter源码:

 * Copyright 2002-2015 the original author or authors.

package org.springframework.orm.hibernate5.support;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate5.SessionFactoryUtils;
import org.springframework.orm.hibernate5.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter; public class OpenSessionInViewFilter extends OncePerRequestFilter { public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory"; private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME; public void setSessionFactoryBeanName(String sessionFactoryBeanName) {
this.sessionFactoryBeanName = sessionFactoryBeanName;
} protected String getSessionFactoryBeanName() {
return this.sessionFactoryBeanName;
}
@Override
protected boolean shouldNotFilterAsyncDispatch() {
return false;
} @Override
protected boolean shouldNotFilterErrorDispatch() {
return false;
} @Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { SessionFactory sessionFactory = lookupSessionFactory(request);
boolean participate = false; WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
String key = getAlreadyFilteredAttributeName(); if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
// Do not modify the Session: just set the participate flag.
participate = true;
}
else {
boolean isFirstRequest = !isAsyncDispatch(request);
if (isFirstRequest || !applySessionBindingInterceptor(asyncManager, key)) {
logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");
Session session = openSession(sessionFactory);
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(sessionFactory, sessionHolder);
asyncManager.registerCallableInterceptor(key, interceptor);
asyncManager.registerDeferredResultInterceptor(key, interceptor);
}
} try {
filterChain.doFilter(request, response);
} finally {
if (!participate) {
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
if (!isAsyncStarted(request)) {
logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
SessionFactoryUtils.closeSession(sessionHolder.getSession());
}
}
}
} protected SessionFactory lookupSessionFactory(HttpServletRequest request) {
return lookupSessionFactory();
} protected SessionFactory lookupSessionFactory() {
if (logger.isDebugEnabled()) {
logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
}
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
} protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
try {
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
} private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) {
if (asyncManager.getCallableInterceptor(key) == null) {
return false;
}
((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession();
return true;
} }

  上面将FlushMode设置MANUAL,查看FlushMode源码:

package org.hibernate;

import java.util.Locale;

public enum FlushMode {
@Deprecated
NEVER ( 0 ), MANUAL( 0 ), COMMIT(5 ), AUTO(10 ), ALWAYS(20 ); private final int level; private FlushMode(int level) {
this.level = level;
} public boolean lessThan(FlushMode other) {
return this.level < other.level;
} @Deprecated
public static boolean isManualFlushMode(FlushMode mode) {
return MANUAL.level == mode.level;
} public static FlushMode interpretExternalSetting(String externalName) {
if ( externalName == null ) {
return null;
} try {
return FlushMode.valueOf( externalName.toUpperCase(Locale.ROOT) );
}
catch ( IllegalArgumentException e ) {
throw new MappingException( "unknown FlushMode : " + externalName );
}
}
}

解决办法:

  在遇到上面错误之后我先打开@Transactional注解查看里面的源码,此注解将readonly默认置为false,所以我们在有此注解的情况下可以进行save或者update操作。源码如下:

 * Copyright 2002-2015 the original author or authors.

package org.springframework.transaction.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor;
import org.springframework.transaction.TransactionDefinition; @Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional { @AliasFor("transactionManager")
String value() default ""; @AliasFor("value")
String transactionManager() default ""; Propagation propagation() default Propagation.REQUIRED; Isolation isolation() default Isolation.DEFAULT; int timeout() default TransactionDefinition.TIMEOUT_DEFAULT; boolean readOnly() default false; Class<? extends Throwable>[] rollbackFor() default {}; String[] rollbackForClassName() default {}; Class<? extends Throwable>[] noRollbackFor() default {}; String[] noRollbackForClassName() default {}; }

解决办法:

  (1)在service层打上@Transactional注解,现在想想这个设计还挺合理,无形之中要求我们打上注解。

  (2)重写上面的过滤器,将打开session的FlushMode设为AUTO:(不推荐这种,因为在进行DML操作的时候最好加上事务控制,防止造成数据库异常)

package cn.qlq.filter;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;
/**
* 重写过滤器去掉session的默认只读属性
* @author liqiang
*
*/
public class MyOpenSessionInViewFilter extends OpenSessionInViewFilter { @Override
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.AUTO);
return session;
}
}

web.xml配置:

    <!--Hibernate的session丢失解决方法 -->
<filter>
<filter-name>myOpenSessionInView</filter-name>
<filter-class>cn.qlq.filter.MyOpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myOpenSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

FlushMode.COMMIT/AUTO

【SSH异常】InvalidDataAccessApiUsageException异常的更多相关文章

  1. 因修改/etc/ssh权限导致的ssh不能连接异常解决方法

    因修改/etc/ssh权限导致的ssh不能连接异常解决方法 现象: $ssh XXX@192.168.5.21 出现以下问题 Read from socket failed: Connection r ...

  2. Java异常处理-----非运行时异常(受检异常)

    非运行时异常(受检异常) 如果出现了非运行时异常必须进行处理throw或者try{}catch(){}处理,否则编译器报错. 1:IOException 使用要导入包import java.io.IO ...

  3. Python档案袋(异常与异常捕获 )

    无异常捕获 程序遇到异常会中断 print( xxx ) print("---- 完 -----") 得到结果为: 有异常捕获 程序遇到异常会进入异常处理,并继续执行下面程序 tr ...

  4. 两种异常(CPU异常、用户模拟异常)的收集

    Windows内核分析索引目录:https://www.cnblogs.com/onetrainee/p/11675224.html 两种异常(CPU异常.用户模拟异常)的收集  文章的核心:异常收集 ...

  5. 重学c#系列——异常续[异常注意事项](七)

    前言 对上节异常的补充,也可以说是异常使用的注意事项. 正文 减少try catch的使用 前面提及到,如果一个方法没有实现该方法的效果,那么就应该抛出异常. 如果有约定那么可以按照约定,如果约定有歧 ...

  6. 异常概念&异常体系和异常分类

    异常概念 异常:指的是程序在执行过程中,出现的非正常的情况,最终会导致JVM的非正常停止. 在Java等面向对象的编程语言中,异常本身是一个类,产生异常就是创建异常对象并抛出了一个异常对象.Java处 ...

  7. spring 整合hibernate注解时候,出现“Unknown entity: com.ssh.entry.Admin; nested exception is org.hibernate.MappingException: Unknown entity: com.ssh.entry.Admin”异常的问题

    今天学习使用ssh框架的时候,出现一个异常,弄了好久才找到,在这记录一下,我的sb错误1.spring整合hibernate,取代*.hbm.xml配置文件   在applicationContext ...

  8. SSH dao层异常 org.hibernate.HibernateException: No Session found for current thread

    解决方法: 在 接口方法中添加 事务注解 即可. public interface IBase<PK extends Serializable, T> { @Transactional v ...

  9. 关于ssh登录出现异常警告:WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

    提示警告信息如下: arnold@WSN:~$ ssh 10.18.46.111 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ...

随机推荐

  1. ContentProvider示例

    http://hi.baidu.com/pekdou/item/b2a070c37552af210831c678 首先,我自己是各初学者,网上一些关于ContentProvider的例子也不少,我自己 ...

  2. 关于cocos2dx 关键字的问题

    今天码代码,在创建新场景的时候,.h文件里  class Game : public cocos2d::Layer没有问题,在Game类里面,声明了它的成员之后,开始在.cpp文件里面实现这个类,到重 ...

  3. [Week17] 个人阅读作业

      个人阅读作业Week17 reading buaa software   解决的问题 这是提出问题的博客链接:http://www.cnblogs.com/SivilTaram/p/4830893 ...

  4. Windows 下 Docker 的简单学习使用过程之二 Docker For windows

    1. Docker For windows 最新版也支持到了 docker ce 18.06 (这个博客的编写时间是 2018.8.17 当时是最新的) 2. 下载安装. 大概500m 左右的安装文件 ...

  5. jenkins 添加 k8s 云

    同事的jenkins 链接自己的 k8s 总是出问题 给出了资料和服务器 进行处理. 同时给出的参考资料:https://blog.csdn.net/diantun00/article/details ...

  6. String类的一些细节

    先看一段代码: public static void main(String[] args) {        String a = "a"+"b"+1;   ...

  7. The Two Routes CodeForces - 601A(水最短路)

    一个完全图 1和n肯定有一条路  不是公路就是铁路  另= 另一个跑遍最短路即可 #include <bits/stdc++.h> #define mem(a, b) memset(a, ...

  8. 解决telnet不是内部命令

    1.telnet在win7下默认是不开启的,所以需要我们自己手动开启.那么首先我们点击开始菜单,找到控制面板项,点击进入: 2.进入程序和功能模块,我们在左边需要选择“打开或关闭windows功能”, ...

  9. 如何整合Office Web Apps至自己开发的系统(二)

    WOPI项目的创建 首先用vs2012创建一个mvc4的程序.如图: 从上一篇我们可以知道,WOPI通讯主要通过两个服务: 一个是CheckFileInfo服务, 一个是GetFile服务. 所以下面 ...

  10. CentOS安装git及使用Gitolite来管理版本库

    首先吐槽一下网上的各种教程,大部分都扯蛋,估计都是些所谓的"编辑"在网上瞎抄来的-- 以下内容都是基于CentOS的服务器端,Mac OS X的客户端. 如果是使用的Windows ...