在用spring.net + Nhibernate进行数据库访问时回出现如下错误:
Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition
至于产生错误的原因可以参考: http://www.diybl.com/course/3_program/java/javajs/20071018/77920.html
当然出现这个错误和保持一个Session有关系
我在web.xml里添加
<add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate12"/>
来确保一个次请求会话中保持使用一个数据会话连接.
那么如何解决这个问题呢? 那就是采用spring.net的事物机制.
添加以下配置脚本
<object id="autoProxyCreator"
type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator, Spring.Aop">
</object>
<!--事务顾问-->
<object id="transactionAdvisor"
type="Spring.Transaction.Interceptor.TransactionAttributeSourceAdvisor, Spring.Data">
<property name="TransactionInterceptor" ref="transactionInterceptor"/>
</object>
<!--事务拦截器-->
<object id="transactionInterceptor"
type="Spring.Transaction.Interceptor.TransactionInterceptor, Spring.Data">
<property name="TransactionManager" ref="HibernateTransactionManager"/>
<!--note do not have converter from string to this property type registered-->
<property name="TransactionAttributeSource" ref="attributeTransactionAttributeSource"/>
</object>
<object id="attributeTransactionAttributeSource"
type="Spring.Transaction.Interceptor.AttributesTransactionAttributeSource, Spring.Data">
</object>
然后在需要事务处理的代码加上方法属性。例如:
[Transaction(Spring.Transaction.TransactionPropagation.Required, ReadOnly = false)]
public void SaveOrUpdate(CompanyInfo info)
{
dao.SaveOrUpdate(info);
}