[[iBATIS-iBATIS]]
iBATIS
~~~~~~

The *ibatis:* component allows you to query, poll, insert, update and
delete data in a relational database using
http://ibatis.apache.org/[Apache iBATIS].

*Prefer MyBatis*

The Apache iBatis project is no longer active. The project is moved
outside Apache and is now know as the MyBatis project. +
Therefore we encourage users to use link:mybatis.html[MyBatis] instead.
This camel-ibatis component will be removed in Camel 3.0.

iBatis do not support Spring 4.x. So you can only use Spring 3.x or
older with iBatis.

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

[source,xml]
------------------------------------------------------------
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-ibatis</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
------------------------------------------------------------

[[iBATIS-URIformat]]
URI format
^^^^^^^^^^

[source,java]
------------------------------
ibatis:statementName[?options]
------------------------------

Where *statementName* is the name in the iBATIS XML configuration 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 iBatis SqlMapConfig file from
the root of the classpath and expected named as `SqlMapConfig.xml`. +
 It uses Spring resource loading so you can define it using `classpath`,
`file` or `http` as prefix to load resources with those schemes. +
 In Camel 2.2 you can configure this on the iBatisComponent with the
`setSqlMapConfig(String)` method.

[[iBATIS-Options]]
Options
^^^^^^^




// component options: START
The iBatis component supports 3 options which are listed below.



{% raw %}
[width="100%",cols="2,1m,7",options="header"]
|=======================================================================
| Name | Java Type | Description
| sqlMapClient | SqlMapClient | To use the given com.ibatis.sqlmap.client.SqlMapClient
| sqlMapConfig | String | Location of iBatis xml configuration file. The default value is: SqlMapConfig.xml loaded from the classpath
| useTransactions | boolean | Whether to use transactions. This option is by default true.
|=======================================================================
{% endraw %}
// component options: END








// endpoint options: START
The iBatis component supports 28 endpoint options which are listed below:

{% raw %}
[width="100%",cols="2,1,1m,1m,5",options="header"]
|=======================================================================
| Name | Group | Default | Java Type | Description
| statement | common |  | String | *Required* The statement name in the iBatis XML mapping file which maps to the query insert update or delete operation you wish to evaluate.
| isolation | common | TRANSACTION_REPEATABLE_READ | String | Transaction isolation level
| useTransactions | common | true | boolean | Whether to use transactions. This option is by default true.
| bridgeErrorHandler | consumer | false | boolean | Allows for bridging the consumer to the Camel routing Error Handler which mean any exceptions occurred while the consumer is trying to pickup incoming messages or the likes will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions that will be logged at WARN/ERROR level and ignored.
| maxMessagesPerPoll | consumer | 0 | int | This option is intended to split results returned by the database pool into the batches and deliver them in multiple exchanges. This integer defines the maximum messages to deliver in single exchange. By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. Set a value of 0 or negative to disable it.
| onConsume | consumer |  | String | Statement to run after data has been processed in the route
| routeEmptyResultSet | consumer | false | boolean | Whether allow empty resultset to be routed to the next hop
| sendEmptyMessageWhenIdle | consumer | false | boolean | If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead.
| strategy | consumer |  | IBatisProcessingStrategy | Allows to plugin a custom IBatisProcessingStrategy to use by the consumer.
| useIterator | consumer | true | boolean | Process resultset individually or as a list
| exceptionHandler | consumer (advanced) |  | ExceptionHandler | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions that will be logged at WARN/ERROR level and ignored.
| exchangePattern | consumer (advanced) |  | ExchangePattern | Sets the exchange pattern when the consumer creates an exchange.
| pollStrategy | consumer (advanced) |  | PollingConsumerPollStrategy | 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.
| statementType | producer |  | StatementType | Mandatory to specify for the producer to control which kind of operation to invoke.
| synchronous | advanced | false | boolean | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported).
| backoffErrorThreshold | scheduler |  | int | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.
| backoffIdleThreshold | scheduler |  | int | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.
| backoffMultiplier | scheduler |  | int | 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.
| delay | scheduler | 500 | long | Milliseconds before the next poll. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour).
| greedy | scheduler | false | boolean | If greedy is enabled then the ScheduledPollConsumer will run immediately again if the previous run polled 1 or more messages.
| initialDelay | scheduler | 1000 | long | Milliseconds before the first poll starts. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour).
| runLoggingLevel | scheduler | TRACE | LoggingLevel | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.
| scheduledExecutorService | scheduler |  | ScheduledExecutorService | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.
| scheduler | scheduler | none | ScheduledPollConsumerScheduler | To use a cron scheduler from either camel-spring or camel-quartz2 component
| schedulerProperties | scheduler |  | Map | To configure additional properties when using a custom scheduler or any of the Quartz2 Spring based scheduler.
| startScheduler | scheduler | true | boolean | Whether the scheduler should be auto started.
| timeUnit | scheduler | MILLISECONDS | TimeUnit | Time unit for initialDelay and delay options.
| useFixedDelay | scheduler | true | boolean | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.
|=======================================================================
{% endraw %}
// endpoint options: END





[[iBATIS-MessageHeaders]]
Message Headers
^^^^^^^^^^^^^^^

Camel will populate the result message, either IN or OUT with a header
with the operationName used:

[width="100%",cols="10%,10%,80%",options="header",]
|=======================================================================
|Header |Type |Description

|`CamelIBatisStatementName` |`String` |The *statementName* used (for example: insertAccount).

|`CamelIBatisResult` |`Object` |The *response* returned from iBatis in any of the operations. For
instance an `INSERT` could return the auto-generated key, or number of
rows etc.
|=======================================================================

[[iBATIS-MessageBody]]
Message Body
^^^^^^^^^^^^

The response from iBatis will only be set as 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 iBatis is always stored in the header
with the key `CamelIBatisResult`.

[[iBATIS-Samples]]
Samples
^^^^^^^

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

[source,java]
--------------------------------------------------
from("activemq:queue:newAccount").
  to("ibatis:insertAccount?statementType=Insert");
--------------------------------------------------

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

Where *insertAccount* is the iBatis ID in the SQL map file:

[source,xml]
------------------------------------------------------------
  <!-- Insert example, using the Account parameter class -->
  <insert id="insertAccount" parameterClass="Account">
    insert into ACCOUNT (
      ACC_ID,
      ACC_FIRST_NAME,
      ACC_LAST_NAME,
      ACC_EMAIL
    )
    values (
      #id#, #firstName#, #lastName#, #emailAddress#
    )
  </insert>
------------------------------------------------------------

[[iBATIS-UsingStatementTypeforbettercontrolofIBatis]]
Using StatementType for better control of IBatis
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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

In the code above we can invoke the iBatis 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
`QueryForList`:

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

[[iBATIS-Scheduledpollingexample]]
Scheduled polling example
+++++++++++++++++++++++++

Since this component does not support scheduled polling, you need to use
another mechanism for triggering the scheduled polls, such as the
link:timer.html[Timer] or link:quartz.html[Quartz] components.

In the sample below we poll the database, every 30 seconds using the
link:timer.html[Timer] component and send the data to the JMS queue:

[source,java]
---------------------------------------------------------------------------------------------------------------------------------------
from("timer://pollTheDatabase?delay=30000").to("ibatis:selectAllAccounts?statementType=QueryForList").to("activemq:queue:allAccounts");
---------------------------------------------------------------------------------------------------------------------------------------

And the iBatis SQL map file used:

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

[[iBATIS-UsingonConsume]]
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 name should be separated by
comma.

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 processed, so we avoid consuming it twice or more.

And the statements in the sqlmap file:

[[iBATIS-SeeAlso]]
See Also
^^^^^^^^

* link:configuring-camel.html[Configuring Camel]
* link:component.html[Component]
* link:endpoint.html[Endpoint]
* link:getting-started.html[Getting Started]

* link:mybatis.html[MyBatis]

