博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【SSH异常】InvalidDataAccessApiUsageException异常
阅读量:6451 次
发布时间:2019-06-23

本文共 9542 字,大约阅读时间需要 31 分钟。

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

openSessionInView
org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
openSessionInView
/*

 

 

  当我在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@Documentedpublic @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
[] rollbackFor() default {}; String[] rollbackForClassName() default {}; Class
[] 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配置:

myOpenSessionInView
cn.qlq.filter.MyOpenSessionInViewFilter
myOpenSessionInView
/*

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

FlushMode.COMMIT/AUTO

转载地址:http://hugwo.baihongyu.com/

你可能感兴趣的文章
c++ 函数声明
查看>>
linux下,免密码登录
查看>>
街道管理
查看>>
hdu 3501 Calculation 2 (欧拉函数)
查看>>
可以免费下载视频素材和模板网站汇总
查看>>
生成包含数字和大小写字母的随机码
查看>>
SPOJ104 Highways,跨越数
查看>>
使用rman备份异机恢复数据库
查看>>
Win7-64bit系统下安装mysql的ODBC驱动
查看>>
node中非常重要的process对象,Child Process模块
查看>>
Webserver管理系列:3、Windows Update
查看>>
Linux内核源码详解——命令篇之iostat[zz]
查看>>
Sqlserver2000联系Oracle11G数据库进行实时数据的同步
查看>>
明年计划
查看>>
ORACLE功能GREATEST功能说明具体实例
查看>>
DataGridView 输入数据验证格式(实例)
查看>>
HDOJ 2151
查看>>
Foundation框架 - 快速创建跨平台的网站页面原型
查看>>
Intel 82599网卡异常挂死原因
查看>>
open-falcon
查看>>