Question

we are using Spring and hibernate in our project and i have noticed that we have defined <tx:annotation-driven /> in sprint context file and if i put @Transactionalannotation for method i am successfully able to interact with database but if i remove @Transactional annotation from method i am getting exception stating that "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here"

is there any way by which i can define all the select operation as non Transactional(i mean without @Transactional annotation) and update and insert as Transactional

Was it helpful?

Solution 2

I am able to resolve this issue by using below code in context xml file.

  <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>

As by default read-only="false" for @Transactional annotation. So we need to make it as read-only="true" for all read operation(Thanks Affe for pointer)

to set read-only="true" for all select select operation make sure that you start your method name from get and rest below code will code for us. you can change your below configuration as per your need.

 <tx:method name="get*" read-only="true"/> 

For more information you can refer to below link

Spring Docs

OTHER TIPS

Using @Transactional(readOnly=true) is usually the best thing for select-only operations. Using hibernate in auto-commit mode can be wasteful when multiple select statements are needed to complete an operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top