在使用了Spring提供的OpenSessionInViewFilter来在一个请求中保持hibernate的session推迟关闭后,会出现如下报错:
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
原因:
这是因为Spring默认将一个名为“readOnly”的属性设置成为true,导致只能对数据库进行“读”操作,不允许进行“写”操作。
解决:
由于我使用的是Annotation的方式配置的bean,故需要在DAO层的实现类上加上如下注释即可:
@Transactional(readOnly = false)
对于使用beans.xml文件配置的情况,可自行修改beans.xml文件内容。