[英]Transactions in Spring/hibernate
我们在项目中使用Spring和hibernate,我注意到我们已经在sprint上下文文件中定义了<tx:annotation-driven />
如果我为方法添加@Transactional
注释我成功地能够与数据库交互但是如果我删除来自方法的@Transactional
注释我正在获得异常,声明"No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here"
是否有任何方法可以将所有选择操作定义为非Transactional(我的意思是没有@Transactional
注释)并更新并插入为Transactional
使用@Transactional(readOnly=true)
通常是仅选择操作的最佳选择。 当需要多个select语句来完成操作时,在自动提交模式下使用hibernate会很浪费。
我可以通过在上下文xml文件中使用以下代码来解决此问题。
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allServiceMethods" expression="execution(* com.test.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServiceMethods"/>
</aop:config>
对于@Transactional
注释,默认情况下read-only="false"
。 因此,对于所有读取操作,我们需要将其设置为read-only="true"
(感谢指针的Affe)
为所有select select操作设置read-only="true"
确保从get
和rest开始你的方法名称代码将为我们编码。 您可以根据需要更改以下配置。
<tx:method name="get*" read-only="true"/>
有关更多信息,请参阅以下链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.