【SSH异常】InvalidDataAccessApiUsageException异常
今天在整合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异常的更多相关文章
- 因修改/etc/ssh权限导致的ssh不能连接异常解决方法
因修改/etc/ssh权限导致的ssh不能连接异常解决方法 现象: $ssh XXX@192.168.5.21 出现以下问题 Read from socket failed: Connection r ...
- Java异常处理-----非运行时异常(受检异常)
非运行时异常(受检异常) 如果出现了非运行时异常必须进行处理throw或者try{}catch(){}处理,否则编译器报错. 1:IOException 使用要导入包import java.io.IO ...
- Python档案袋(异常与异常捕获 )
无异常捕获 程序遇到异常会中断 print( xxx ) print("---- 完 -----") 得到结果为: 有异常捕获 程序遇到异常会进入异常处理,并继续执行下面程序 tr ...
- 两种异常(CPU异常、用户模拟异常)的收集
Windows内核分析索引目录:https://www.cnblogs.com/onetrainee/p/11675224.html 两种异常(CPU异常.用户模拟异常)的收集 文章的核心:异常收集 ...
- 重学c#系列——异常续[异常注意事项](七)
前言 对上节异常的补充,也可以说是异常使用的注意事项. 正文 减少try catch的使用 前面提及到,如果一个方法没有实现该方法的效果,那么就应该抛出异常. 如果有约定那么可以按照约定,如果约定有歧 ...
- 异常概念&异常体系和异常分类
异常概念 异常:指的是程序在执行过程中,出现的非正常的情况,最终会导致JVM的非正常停止. 在Java等面向对象的编程语言中,异常本身是一个类,产生异常就是创建异常对象并抛出了一个异常对象.Java处 ...
- 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 ...
- SSH dao层异常 org.hibernate.HibernateException: No Session found for current thread
解决方法: 在 接口方法中添加 事务注解 即可. public interface IBase<PK extends Serializable, T> { @Transactional v ...
- 关于ssh登录出现异常警告:WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
提示警告信息如下: arnold@WSN:~$ ssh 10.18.46.111 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ...
随机推荐
- 链家鸟哥:从留级打架问题学生到PHP大神,他的人生驱动力竟然是?
链家鸟哥:从留级打架问题学生到PHP大神,他的人生驱动力竟然是?| 二叉树短视频 http://mp.weixin.qq.com/s/D4l_zOpKDakptCM__4hLrQ 从问题劝退学生到高考 ...
- 【SE】Week3 : 四则运算式生成评分工具Extension&Release Version(结对项目)
Foreword 此次的结对项目终于告一段落,除了本身对软件开发的整体流程有了更深刻的了解外,更深刻的认识应该是结对编程对这一过程的促进作用. 在此想形式性但真心地啰嗦几句,十分感谢能端同学能够不厌其 ...
- 审评(HelloWorld团队)
炸弹人:我觉得炸弹人的构想很不错,很像以前玩的qq堂,不过上课时讲的不够深入,我没有找到项目的思路,项目的介绍也很粗糙,后面说的目标很大,希望你可以实现,我觉得越多的功能,就意味着越多的工作量,总的来 ...
- 第二个Sprint
能够实现三个数,两个操作符的四则运算.
- [Week17] 个人阅读作业
个人阅读作业Week17 reading buaa software 解决的问题 这是提出问题的博客链接:http://www.cnblogs.com/SivilTaram/p/4830893 ...
- Uploadify提示-Failed,上传不了文件,跟踪onUploadError事件,errorMsg:2156 SecurityError Error #2156 null
在使用Uploadify上传文件时,提示-Failed,上传不了文件 折腾中.....,没有结果.....%>_<%... 于是跟踪onUploadError事件,发现 errorMsg: ...
- [51CTO]服务器虚拟化开源技术主流架构之争
服务器虚拟化开源技术主流架构之争 http://virtual.51cto.com/art/201812/589084.htm 大部分客户已经是KVM+OpenStack的架构了 我所见到的 工商云 ...
- Enum 枚举值 (一) 获取描述信息
封装了方法: public static class EnumOperate { public class BaseDescriptionAttribute : DescriptionAttribut ...
- 做前端好还是Java好?
做前端好还是Java好?看这三方面 转载 2017年11月14日 00:00:00 1047这几年来伴随着互联网的迅速发展,新兴互联网产业的兴起,传统行业也逐渐开始互联网化,使得互联网职业在这样的背景 ...
- 自学Aruba1.1-WLAN一些基本常识
点击返回:自学Aruba之路 自学Aruba1.1-WLAN一些基本常识 1. LAN.WAN.WLAN.WIFI术语 1.1 局域网(Local Area Network,LAN) 是指在某一区域内 ...