您的位置:首页 > 运维架构

Write operations are not allowed in read-only mode (FlushMode.MANUAL):

2015-01-19 16:40 381 查看
在使用spring+hibernate进行数据update和delete时,出现了

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.异常。网上查了些资料,解释了Spring在TransactionDefinition接口中规定了事务传播的行为,规定了事务方法和事务方法发生嵌套如何进行传播。闲话少说,当出现这种错误时,我是这么做的。

beans.xml中配置为:

<!-- 配置数据源 -->
	<bean id="MyDataSource" destroy-method="close"
      					class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
	    <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
	    <property name="username" value="root"/>
	    <property name="password" value="1234"/>
	</bean>
	
   <!--定义自己的sessionFactory-->
  <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="MyDataSource"/>
    <property name="annotatedClasses">
      <list>
        <value>com.nhx.model.User</value>
      </list>
    </property>
    <property name="hibernateProperties">
   	 <props>
    	<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    	<prop key="hibernate.show_sql">true</prop>
    	<prop key="hibernate.format_sql">true</prop>
   	 </props>
    </property>
  </bean>
         
  <!--定义自己的hibernateTemplate-->
  <bean id="hibernateTemplate"  
        class="org.springframework.orm.hibernate4.HibernateTemplate">
 	<property name="sessionFactory" ref="mySessionFactory"/>
 </bean>
 
<!--定义hibernate的事务管理器-->
 <bean id="txManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <!--关联sessionFactory-->
           <property name="sessionFactory" ref="mySessionFactory" />
	</bean>

 <!--定义切面类-->
 <aop:config>
	<aop:pointcut id="bussinessService"
                <!--你需要用到事务处理的方法关联-->
                expression="execution(public * com.nhx.dao.impl.*.*(..))" />
		<aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice"/>
	</aop:config>
 
  <!--spring建议中规定你的update\delete\select\add方法中事务的处理方式-->
 <tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
                         <!--定义事务为只读模式-->
                        <tx:method name="exists" read-only="true" />
                         <!--定义com.nhx.dao.impl包中的任何前缀为update的方法事务方法,sessionFactory不存在时,自动建立-->
                         <!--这也是解决本问题的关键方法-->
                        <tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice></span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐