Search code examples
apache-cameltransactionscopetransactional

<transacted /> is not working in apache camel


I have a database with two tables, accountsA and accountsB. I want to do some updates on both of these database tables in the same transaction scope so I used component, but when an exception is happening in updating accountsB, the updates of accountsA is being continued, I need my database to do both updates together or none of them.

for testing that the transacted component is working correctly, I made a change in the name of the accountB table name, an exception accrued. I was expecting that the updating of accountA table will be stop, but it doesn't happened. did I do something wrong?

    <bean id="mysql-ds-local" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/BankDB?relaxAutoCommit=true"/>
  <property name="username" value="root"/>
  <property name="password" value="osslab"/>
  <property name="poolPreparedStatements" value="true"/>
    </bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="mysql-ds-local"/>
</bean>


<camelContext id="camel-jdbc-test" xmlns="http://camel.apache.org/schema/blueprint" >

   <route id="main-route-jdbc">


      <from uri="timer://webinar?period=20000" /> 
       <transacted />
          <to uri="direct:reduceCredit"/>
          <to uri="direct:increaseCredit"/>
    </route>
    <route id="reduceCredit-route">
        <from uri="direct:reduceCredit"/>
        <log message="in direct accountA"/>
        <setBody>
            <constant>update accountsA set credit = credit + 1 where id = 1</constant>
        </setBody>
        <to uri="jdbc:mysql-ds-local" />
    </route>
   <route id="increaseCredit-route">
        <from uri="direct:increaseCredit"/>
        <log message="in direct accountB"/>
        <setBody>
            <constant>update accountsB set credit = credit + 1 where id = 1</constant>
        </setBody>
        <to uri="jdbc:mysql-ds-local" />
    </route>

</camelContext>

Solution

  • Perhaps you just omitted it, but a key element that is missing in your question is a DataSourceTransactionManager that makes your DataSource transactional.

    <bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="myDataSource"/>
    </bean>