224.6.7. トランザクションへの参加
camel-mybatis でトランザクションマネージャーを設定することは、標準の MyBatis SqlMapConfig.xml ファイル外でデータベース設定を外部化する必要があるため、ほとんど少し複雑です。
最初の部分では DataSource の設定が必要です。通常、これは Spring プロキシーでラップする必要があるプール(DBCP または c3p0)です。このプロキシーにより、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>
これは、プロパティープレースホルダーを使用してデータベース設定を外部化できるようにするもう 1 つの利点があります。
その後、トランザクションマネージャーは、外側の DataSource を管理するように設定されます。
<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>