235.7.7. 参与事务
在 camel-mybatis 下设置事务管理器可能只是一小的,因为它涉及在标准的 MyBatis SqlMapConfig.xml 文件外部提供数据库配置。
第一部分需要设置 DataSource。这通常是一个池(DBCP 或 c3p0),它需要嵌套在 Spring 代理中。此代理可让 DataSource 的非 Spring 使用参与 Spring 事务(即 MyBatis SqlSessionFactory 只是此目的)。
<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg>
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="org.postgresql.Driver"/>
<property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/myDatabase"/>
<property name="user" value="myUser"/>
<property name="password" value="myPassword"/>
</bean>
</constructor-arg>
</bean>这样做的额外优点是使数据库配置通过使用属性占位符进行外部化。
然后,一个事务管理器被被配置为管理 外部数据源 :
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
一个 mybatis-spring SqlSessionFactoryBean,然后包装相同的 DataSource :
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- standard mybatis config file -->
<property name="configLocation" value="/META-INF/SqlMapConfig.xml"/>
<!-- externalised mappers -->
<property name="mapperLocations" value="classpath*:META-INF/mappers/**/*.xml"/>
</bean>然后,camel-mybatis 组件被配置为使用该工厂:
<bean id="mybatis" class="org.apache.camel.component.mybatis.MyBatisComponent">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>最后,一个事务策略在交易管理器的顶部定义,然后可以正常使用:
<bean id="PROPAGATION_REQUIRED" class="org.apache.camel.spring.spi.SpringTransactionPolicy">
<property name="transactionManager" ref="txManager"/>
<property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/>
</bean>
<camelContext id="my-model-context" xmlns="http://camel.apache.org/schema/spring">
<route id="insertModel">
<from uri="direct:insert"/>
<transacted ref="PROPAGATION_REQUIRED"/>
<to uri="mybatis:myModel.insert?statementType=Insert"/>
</route>
</camelContext>