Camel Components

MyBatis

Since Camel 2.7

Both producer and consumer are supported

The MyBatis component allows you to query, poll, insert, update and delete data in a relational database using MyBatis.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-mybatis</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

mybatis:statementName[?options]

Where statementName is the statement name in the MyBatis XML mapping file which maps to the query, insert, update or delete operation you wish to evaluate.

You can append query options to the URI in the following format, ?option=value&option=value&…​

This component will by default load the MyBatis SqlMapConfig file from the root of the classpath with the expected name of SqlMapConfig.xml.
If the file is located in another location, you will need to configure the configurationUri option on the MyBatisComponent component.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The MyBatis component supports the following options which are listed below.

Name Description Default Type

configurationUri (common)

The location of the MyBatis XML configuration file, which the component reads to build the SqlSessionFactory when the sqlSessionFactory option is not set. It is loaded from the classpath, or prefix it with file: or http: for another location.

SqlMapConfig.xml

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

sqlSessionFactory (advanced)

Autowired The org.apache.ibatis.session.SqlSessionFactory that opens the MyBatis sessions of all the endpoints of this component. If not set or autowired, the component builds one from the file of the configurationUri option.

SqlSessionFactory

healthCheckConsumerEnabled (health)

Used for enabling or disabling all consumer based health checks from this component.

true

boolean

healthCheckProducerEnabled (health)

Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true.

true

boolean

Endpoint Options

The MyBatis endpoint is configured using URI syntax:

mybatis:statement

With the following path and query parameters:

Path Parameters

Name Description Default Type

statement (common)

Required The ID of the mapped statement to run, as a mapper XML file or a mapper annotation of the MyBatis configuration declares it, for example selectAllAccounts, or qualified by its namespace. The consumer runs it as a select without parameter on each poll, and the producer as the statementType option says.

String

Query Parameters

Name Description Default Type

outputHeader (common)

The name of the header to store the result in, instead of the message body, which then stays unchanged. The producer then does not set the CamelMyBatisResult header, and the consumer puts each polled row, or the List of rows, in this header and leaves the body empty.

String

maxMessagesPerPoll (consumer)

The maximum number of exchanges that the consumer processes in one poll. The select still reads all the rows, the other rows are not routed in that poll, and the next poll runs the select again. A value of 0 or less means no limit.

0

int

onConsume (consumer)

The ID of the mapped statement that the consumer runs as an update after an exchange is processed successfully, with the row (or the List of rows) as parameter, for example to mark the row as processed. Separate several statements with commas. A failed or rollback only exchange does not run it, so the next poll selects the row again.

String

routeEmptyResultSet (consumer)

Whether the consumer routes an exchange with an empty List when the select returns no rows. It applies only when useIterator is false; otherwise no rows means no exchange.

false

boolean

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

transacted (consumer)

Whether the consumer stops processing the other rows of the poll when an exchange fails or is marked rollback only, and fails the poll with that exception. It does not start a transaction: the select and the onConsume statements each run in their own MyBatis session.

false

boolean

useIterator (consumer)

Whether the consumer routes each row of the select in its own exchange. If false, it routes all the rows of a poll as one List in one exchange.

true

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

pollStrategy (consumer (advanced))

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

PollingConsumerPollStrategy

processingStrategy (consumer (advanced))

A custom org.apache.camel.component.mybatis.MyBatisProcessingStrategy that runs the select of a poll and the onConsume statements. The default runs the select with selectList and each onConsume statement with update, each in its own SqlSession.

MyBatisProcessingStrategy

executorType (producer)

The MyBatis executor type of the session that the producer opens for each message: SIMPLE prepares a new statement for each call, REUSE reuses the prepared statements, and BATCH batches the updates and sends them together when the session is committed. With BATCH, MyBatis returns a fixed placeholder value instead of the count of rows of an insert, update or delete. If not set, the defaultExecutorType of the MyBatis configuration is used.

Enum values:

  • SIMPLE

  • REUSE

  • BATCH

SIMPLE

ExecutorType

inputHeader (producer)

The name of the header that holds the parameter of the statement, read instead of the message body. If not set, the producer reads the message body.

String

statementType (producer)

The kind of operation that the producer runs the statement as. The producer requires it. SelectOne fails when the select returns more than one row. Insert, Update and Delete run the statement once per element when the parameter is a Collection, an array or an Iterator, while InsertList, UpdateList and DeleteList run it once with the whole List, for a foreach in the statement.

Enum values:

  • SelectOne

  • SelectList

  • Insert

  • InsertList

  • Update

  • UpdateList

  • Delete

  • DeleteList

StatementType

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

int

delay (scheduler)

Milliseconds before the next poll.

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

healthCheckMaxPollDuration (scheduler)

How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off.

0

long

initialDelay (scheduler)

Milliseconds before the first poll starts.

1000

long

repeatCount (scheduler)

Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.

0

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

ScheduledExecutorService

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler.

none

Object

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler.

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

Message Headers

The MyBatis component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelMyBatisResult (producer)

Constant: MYBATIS_RESULT

The result that the producer sets: the row or the List of rows of a select, the count of rows of an insert, update or delete (of the last run for a List), or for mybatis-bean what the method returns. A generated key is not in it: MyBatis sets that key on the parameter object. With outputHeader, the result is in that header instead.

Object

CamelMyBatisStatementName (common)

Constant: MYBATIS_STATEMENT_NAME

The ID of the mapped statement that ran, from the statement option, for example insertAccount. The consumer and the producer set it.

String

Message Body

The message body at each side of the MyBatis component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

unknown

One row of the select per message, as the resultType or resultMap of the statement maps it: a bean, a Map or a single value, and null for a row of only nulls. With useIterator=false a List of all the rows in one message; with outputHeader the row goes in that header and the body is null.

  • With useIterator=false: list

Not known when outputHeader is set.

Producer input

any

The parameter of the statement, given to MyBatis as it is, without type conversion: it must fit the parameterType, so the text 123 fails an int parameter. A bean or a Map for several parameters; no body runs the statement without one. Insert, Update and Delete run once per element of a List, an array or an Iterator, the List variants once with the whole List. With inputHeader the parameter is that header and the body is not read.

Producer output

unknown

By the statementType, which the producer needs: SelectOne gives the one row as the statement maps it (a bean, a Map or a value), or null for no row; SelectList a List of the rows. Insert, Update and Delete leave the body unchanged, with the count of rows in the CamelMyBatisResult header. With outputHeader the result goes in that header and the body is unchanged.

  • With statementType=SelectOne: unknown

  • With statementType=SelectList: list

  • With statementType=Insert: unchanged

  • With statementType=InsertList: unchanged

  • With statementType=Update: unchanged

  • With statementType=UpdateList: unchanged

  • With statementType=Delete: unchanged

  • With statementType=DeleteList: unchanged

Not known when outputHeader is set.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Message Body

The response from MyBatis will only be set as the body if it’s a SELECT statement. That means, for example, for INSERT statements Camel will not replace the body. This allows you to continue routing and keep the original body. The response from MyBatis is stored in the header with the key CamelMyBatisResult, or in the header that the outputHeader option names, which leaves the body unchanged for a SELECT as well. This is the same for an InOnly and an InOut exchange.

When the body (or the header that the inputHeader option names) is null, an Insert, Update or Delete runs the statement without a parameter. If the statement has parameters, such as #{id}, the producer fails with an IllegalArgumentException instead of running the statement with NULL for every parameter, which would insert a row of nulls, or set columns to null in every row an UPDATE without a WHERE matches.

Examples

For example, if you wish to consume beans from a JMS queue and insert them into a database, you could do the following:

  • Java

  • XML

  • YAML

from("activemq:queue:newAccount")
    .to("mybatis:insertAccount?statementType=Insert");
<route>
  <from uri="activemq:queue:newAccount"/>
  <to uri="mybatis:insertAccount?statementType=Insert"/>
</route>
- route:
    from:
      uri: activemq:queue:newAccount
      steps:
        - to:
            uri: mybatis:insertAccount
            parameters:
              statementType: Insert

Notice we have to specify the statementType, as we need to instruct Camel which kind of operation to invoke.

Where insertAccount is the MyBatis ID in the SQL mapping file:

  <!-- Insert example, using the Account parameter class -->
  <insert id="insertAccount" parameterType="Account">
    insert into ACCOUNT (
      ACC_ID,
      ACC_FIRST_NAME,
      ACC_LAST_NAME,
      ACC_EMAIL
    )
    values (
      #{id}, #{firstName}, #{lastName}, #{emailAddress}
    )
  </insert>

Using StatementType for better control of MyBatis

When routing to an MyBatis endpoint, you will want more fine-grained control so you can control whether the SQL statement to be executed is a SELECT, UPDATE, DELETE or INSERT etc. So for instance if we want to route to an MyBatis endpoint in which the IN body contains parameters to a SELECT statement we can do:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("mybatis:selectAccountById?statementType=SelectOne")
    .to("mock:result");
<route>
  <from uri="direct:start"/>
  <to uri="mybatis:selectAccountById?statementType=SelectOne"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: mybatis:selectAccountById
            parameters:
              statementType: SelectOne
        - to:
            uri: mock:result

In the code above we can invoke the MyBatis statement selectAccountById and the IN body should contain the account id we want to retrieve, such as an Integer type.

We can do the same for some of the other operations, such as SelectList:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("mybatis:selectAllAccounts?statementType=SelectList")
    .to("mock:result");
<route>
  <from uri="direct:start"/>
  <to uri="mybatis:selectAllAccounts?statementType=SelectList"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: mybatis:selectAllAccounts
            parameters:
              statementType: SelectList
        - to:
            uri: mock:result

And the same for UPDATE, where we can send an Account object as the IN body to MyBatis:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("mybatis:updateAccount?statementType=Update")
    .to("mock:result");
<route>
  <from uri="direct:start"/>
  <to uri="mybatis:updateAccount?statementType=Update"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: mybatis:updateAccount
            parameters:
              statementType: Update
        - to:
            uri: mock:result

Using InsertList StatementType

MyBatis allows you to insert multiple rows using its for-each batch driver. To use this, you need to use the <foreach> in the mapper XML file. For example, as shown below:

<!-- Batch Insert example, using the Account parameter class -->
<insert id="batchInsertAccount" parameterType="java.util.List">
    insert into ACCOUNT (
    ACC_ID,
    ACC_FIRST_NAME,
    ACC_LAST_NAME,
    ACC_EMAIL
    )
    values (
    <foreach item="Account" collection="list" open="" close="" separator="),(">
        #{Account.id}, #{Account.firstName}, #{Account.lastName}, #{Account.emailAddress}
    </foreach>
    )
</insert>

Then you can insert multiple rows, by sending a Camel message to the mybatis endpoint which uses the InsertList statement type, as shown below:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("mybatis:batchInsertAccount?statementType=InsertList")
    .to("mock:result");
<route>
  <from uri="direct:start"/>
  <to uri="mybatis:batchInsertAccount?statementType=InsertList"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: mybatis:batchInsertAccount
            parameters:
              statementType: InsertList
        - to:
            uri: mock:result

Using UpdateList StatementType

MyBatis allows you to update multiple rows using its for-each batch driver. To use this, you need to use the <foreach> in the mapper XML file. For example, as shown below:

<update id="batchUpdateAccount" parameterType="java.util.Map">
    update ACCOUNT set
    ACC_EMAIL = #{emailAddress}
    where
    ACC_ID in
    <foreach item="Account" collection="list" open="(" close=")" separator=",">
        #{Account.id}
    </foreach>
</update>

Then you can update multiple rows, by sending a Camel message to the mybatis endpoint which uses the UpdateList statement type, as shown below:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("mybatis:batchUpdateAccount?statementType=UpdateList")
    .to("mock:result");
<route>
  <from uri="direct:start"/>
  <to uri="mybatis:batchUpdateAccount?statementType=UpdateList"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: mybatis:batchUpdateAccount
            parameters:
              statementType: UpdateList
        - to:
            uri: mock:result

Using DeleteList StatementType

MyBatis allows you to delete multiple rows using its for-each batch driver. To use this, you need to use the <foreach> in the mapper XML file. For example, as shown below:

<delete id="batchDeleteAccountById" parameterType="java.util.List">
    delete from ACCOUNT
    where
    ACC_ID in
    <foreach item="AccountID" collection="list" open="(" close=")" separator=",">
        #{AccountID}
    </foreach>
</delete>

Then you can delete multiple rows, by sending a Camel message to the mybatis endpoint which uses the DeleteList statement type, as shown below:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("mybatis:batchDeleteAccount?statementType=DeleteList")
    .to("mock:result");
<route>
  <from uri="direct:start"/>
  <to uri="mybatis:batchDeleteAccount?statementType=DeleteList"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: mybatis:batchDeleteAccount
            parameters:
              statementType: DeleteList
        - to:
            uri: mock:result

Notice on InsertList, UpdateList and DeleteList StatementTypes

Parameter of any type (List, Map, etc.) can be passed to mybatis, and an end user is responsible for handling it as required with the help of mybatis dynamic queries capabilities.

Scheduled polling example

This component supports scheduled polling and can therefore be used as a Polling Consumer. For example, to poll the database every minute:

  • Java

  • XML

  • YAML

from("mybatis:selectAllAccounts?delay=60000")
    .to("activemq:queue:allAccounts");
<route>
  <from uri="mybatis:selectAllAccounts?delay=60000"/>
  <to uri="activemq:queue:allAccounts"/>
</route>
- route:
    from:
      uri: mybatis:selectAllAccounts
      parameters:
        delay: 60000
      steps:
        - to:
            uri: activemq:queue:allAccounts

Alternatively you can use another mechanism for triggering the scheduled polls, such as the Timer or Quartz components. In the sample below we poll the database, every 30 seconds using the Timer component and send the data to the JMS queue:

  • Java

  • XML

  • YAML

from("timer://pollTheDatabase?delay=30000")
    .to("mybatis:selectAllAccounts")
    .to("activemq:queue:allAccounts");
<route>
  <from uri="timer://pollTheDatabase?delay=30000"/>
  <to uri="mybatis:selectAllAccounts"/>
  <to uri="activemq:queue:allAccounts"/>
</route>
- route:
    from:
      uri: timer:pollTheDatabase
      parameters:
        delay: 30000
      steps:
        - to:
            uri: mybatis:selectAllAccounts
        - to:
            uri: activemq:queue:allAccounts

And the MyBatis SQL mapping file used:

  <!-- Select with no parameters using the result map for Account class. -->
  <select id="selectAllAccounts" resultMap="AccountResult">
    select * from ACCOUNT
  </select>

Using onConsume

This component supports executing statements after data have been consumed and processed by Camel. This allows you to do post updates in the database. Notice all statements must be UPDATE statements. Camel supports executing multiple statements whose names should be separated by commas.

The route below illustrates we execute the consumeAccount statement data is processed. This allows us to change the status of the row in the database to process, so we avoid consuming it twice or more.

  • Java

  • XML

  • YAML

from("mybatis:selectUnprocessedAccounts?onConsume=consumeAccount")
    .to("mock:results");
<route>
  <from uri="mybatis:selectUnprocessedAccounts?onConsume=consumeAccount"/>
  <to uri="mock:results"/>
</route>
- route:
    from:
      uri: mybatis:selectUnprocessedAccounts
      parameters:
        onConsume: consumeAccount
      steps:
        - to:
            uri: mock:results

And the statements in the sqlmap file:

<update id="consumeAccount" parameterType="Account">
    update ACCOUNT set PROCESSED = true where ACC_ID = #{id}
</update>

The statements only run when the exchange completed successfully. If the exchange failed (or was marked rollback only), they are not run and the row is consumed again by the next poll, so a row that always fails is consumed again at every poll. Handle the exception in the route (for example with onException(…​).handled(true)) to run the statements for a failed exchange anyway.

Participating in transactions

Setting up a transaction manager under camel-mybatis can be a little bit fiddly, as it involves externalising the database configuration outside the standard MyBatis SqlMapConfig.xml file.

The first part requires the setup of a DataSource. This is typically a pool (either DBCP, or c3p0), which needs to be wrapped in a Spring proxy. This proxy enables non-Spring use of the DataSource to participate in Spring transactions (the MyBatis SqlSessionFactory does just this).

XML-only: Spring bean declaration for transaction-aware DataSource proxy
<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>

This has the additional benefit of enabling the database configuration to be externalised using property placeholders.

A transaction manager is then configured to manage the outermost DataSource:

XML-only: Spring bean declaration for `DataSourceTransactionManager`
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

A mybatis-spring SqlSessionFactoryBean then wraps that same DataSource:

XML-only: Spring bean declaration for MyBatis `SqlSessionFactoryBean`
<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>

The camel-mybatis component is then configured with that factory:

XML-only: Spring bean declaration for MyBatisComponent with `SqlSessionFactory`
<bean id="mybatis" class="org.apache.camel.component.mybatis.MyBatisComponent">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

Finally, a transaction policy is defined over the top of the transaction manager, which can then be used as usual:

  • Java

  • XML

  • YAML

from("direct:insert")
    .policy("PROPAGATION_REQUIRED")
    .to("mybatis:myModel.insert?statementType=Insert");
<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>
- route:
    from:
      uri: direct:insert
      steps:
        - policy:
            ref: PROPAGATION_REQUIRED
            steps:
              - to:
                  uri: mybatis:myModel.insert
                  parameters:
                    statementType: Insert

MyBatis Spring Boot Starter integration

Spring Boot users can use mybatis-spring-boot-starter artifact provided by the mybatis team

<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>3.0.3</version>
</dependency>

in particular, autoconfigured beans from mybatis-spring-boot-starter can be used as follows:

#application.properties
camel.component.mybatis.sql-session-factory = #sqlSessionFactory