[英]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.