【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

原文地址:https://www.cnblogs.com/qlqwjy/p/9535500.html