org.springframework.dao.InvalidDataAccessApiUsageException 原因和解决

在springmvc 和 hibernate 整合开发中出现一下错误

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.

原因:在bean配置的时候开启了只读过滤:

 
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="ad*" propagation="REQUIRED" />
            <tx:method name="updat*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED" />
        tx:attributes>
    tx:advice>

所有以get 或者query 开头的方法都会被只读过滤,无法进行更新 插入 删除操作:包括你用get* (query*)方法 调用update* (这个方法里面进行了插入 更新 删除操作)方法

解决方法:
1.直接一点,直接把可读去掉 设置全操作

<tx:advice id="txAdvice" transaction-manager="transactionManager">
        
        <tx:attributes>
            <tx:method name="get*" propagation="REQUIRED" />
            <tx:method name="query*" propagation="REQUIRED" />
            <tx:method name="ad*" propagation="REQUIRED" />
            <tx:method name="updat*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED" />
        tx:attributes>
    tx:advice>

2.网上大部分的blog中写的方法 web.xml 中配置OpenSessionInViewFilter过滤
下面代码 要放在spring核心控制器配置之前
不过配置完之后 没什么用 也不知道为什么

 <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>
            /WEB-INF/Springmvc-servlet.xml
        param-value>
    context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    <filter>
        <filter-name>hibernateFilterfilter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilterfilter-class>
        <init-param>
            <param-name>flushModeparam-name>
            <param-value>AUTOparam-value>
        init-param>
        <init-param>
            <param-name>singleSessionparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>hibernateFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

你可能感兴趣的:(springmvc,hibernate)