出错代码如下:
@Autowired
@Qualifier("hibernateTemplate")
HibernateTemplate userDao;
@Override
public String addUser(TUser user) {
userDao.save(user);
return JSON.toJSONString(ResultVOUtil.success());
}
报错信息如下:
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.
排查思路:
通常当使用OpenSessionInViewFilter并在Spring管理的事务之外进行持久化操作时会发生这个错误。这个filter默认会将Hibernate session的flush mode设置为FlushMode.NEVER,在读写事务期间,transaction manager会暂时将flush mode改为FlushMode.AUTO。在每个事务结束时,flush mode会被重置。
解决方法是将该方法加上@Transactional注解以启用事务管理。
然而,有时事务仍会失效。这可能是因为Spring的配置有误,没有正确扫描到Service包。
<context:component-scan base-package="com">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
通过以上排查方法,问题得以解决。
参考:
https://stackoverflow.com/questions/6810158/java-hibernate-write-operations-are-not-allowed-in-read-only-mode
https://docs.spring.io/spring-framework/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.html
https://blog.csdn.net/weixin_43564627/article/details/121354260