--- apiVersion: v1 kind: List items: - apiVersion: v1 kind: ConfigMap metadata: labels: funktion.fabric8.io/kind: Connector provider: fabric8 project: connector-mybatis version: 1.1.30 group: io.fabric8.funktion.connector name: mybatis data: deployment.yml: | --- apiVersion: extensions/v1beta1 kind: Deployment metadata: labels: funktion.fabric8.io/kind: Subscription connector: mybatis spec: replicas: 1 template: metadata: labels: funktion.fabric8.io/kind: Subscription connector: mybatis spec: containers: - image: fabric8/connector-mybatis:1.1.30 name: connector schema.yml: | --- component: kind: component scheme: mybatis syntax: mybatis:statement title: MyBatis description: Performs a query poll insert update or delete in a relational database using MyBatis. label: database,sql deprecated: false async: false javaType: org.apache.camel.component.mybatis.MyBatisComponent groupId: org.apache.camel artifactId: camel-mybatis version: 2.18.1 componentProperties: sqlSessionFactory: kind: property type: object javaType: org.apache.ibatis.session.SqlSessionFactory deprecated: false secret: false description: To use the SqlSessionFactory configurationUri: kind: property type: string javaType: java.lang.String deprecated: false secret: false description: 'Location of MyBatis xml configuration file. The default value is: SqlMapConfig.xml loaded from the classpath' properties: statement: kind: path group: common required: true type: string javaType: java.lang.String deprecated: false secret: false description: The statement name in the MyBatis XML mapping file which maps to the query insert update or delete operation you wish to evaluate. outputHeader: kind: parameter group: common type: string javaType: java.lang.String deprecated: false secret: false description: Store the query result in a header instead of the message body. By default outputHeader == null and the query result is stored in the message body any existing content in the message body is discarded. If outputHeader is set the value is used as the name of the header to store the query result and the original message body is preserved. Setting outputHeader will also omit populating the default CamelMyBatisResult header since it would be the same as outputHeader all the time. bridgeErrorHandler: kind: parameter group: consumer label: consumer type: boolean javaType: boolean optionalPrefix: consumer. deprecated: false secret: false defaultValue: false description: 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. inputHeader: kind: parameter group: consumer label: consumer type: string javaType: java.lang.String deprecated: false secret: false description: User the header value for input parameters instead of the message body. By default inputHeader == null and the input parameters are taken from the message body. If outputHeader is set the value is used and query parameters will be taken from the header instead of the body. maxMessagesPerPoll: kind: parameter group: consumer label: consumer type: integer javaType: int deprecated: false secret: false defaultValue: "0" description: 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: kind: parameter group: consumer label: consumer type: string javaType: java.lang.String optionalPrefix: consumer. deprecated: false secret: false description: Statement to run after data has been processed in the route routeEmptyResultSet: kind: parameter group: consumer label: consumer type: boolean javaType: boolean optionalPrefix: consumer. deprecated: false secret: false defaultValue: false description: Whether allow empty resultset to be routed to the next hop sendEmptyMessageWhenIdle: kind: parameter group: consumer label: consumer type: boolean javaType: boolean optionalPrefix: consumer. deprecated: false secret: false defaultValue: false description: If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead. transacted: kind: parameter group: consumer label: consumer type: boolean javaType: boolean deprecated: false secret: false defaultValue: false description: Enables or disables transaction. If enabled then if processing an exchange failed then the consumer break out processing any further exchanges to cause a rollback eager useIterator: kind: parameter group: consumer label: consumer type: boolean javaType: boolean optionalPrefix: consumer. deprecated: false secret: false defaultValue: true description: Process resultset individually or as a list exceptionHandler: kind: parameter group: consumer (advanced) label: consumer,advanced type: object javaType: org.apache.camel.spi.ExceptionHandler optionalPrefix: consumer. deprecated: false secret: false description: 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: kind: parameter group: consumer (advanced) label: consumer,advanced type: string javaType: org.apache.camel.ExchangePattern enum: - InOnly - RobustInOnly - InOut - InOptionalOut - OutOnly - RobustOutOnly - OutIn - OutOptionalIn deprecated: false secret: false description: Sets the exchange pattern when the consumer creates an exchange. pollStrategy: kind: parameter group: consumer (advanced) label: consumer,advanced type: object javaType: org.apache.camel.spi.PollingConsumerPollStrategy optionalPrefix: consumer. deprecated: false secret: false description: 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. executorType: kind: parameter group: producer label: producer type: string javaType: org.apache.ibatis.session.ExecutorType enum: - SIMPLE - REUSE - BATCH deprecated: false secret: false defaultValue: SIMPLE description: The executor type to be used while executing statements. simple - executor does nothing special. reuse - executor reuses prepared statements. batch - executor reuses statements and batches updates. statementType: kind: parameter group: producer label: producer type: string javaType: org.apache.camel.component.mybatis.StatementType enum: - SelectOne - SelectList - Insert - InsertList - Update - UpdateList - Delete - DeleteList deprecated: false secret: false description: Mandatory to specify for the producer to control which kind of operation to invoke. synchronous: kind: parameter group: advanced label: advanced type: boolean javaType: boolean deprecated: false secret: false defaultValue: false description: Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). backoffErrorThreshold: kind: parameter group: scheduler label: consumer,scheduler type: integer javaType: int optionalPrefix: consumer. deprecated: false secret: false description: The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. backoffIdleThreshold: kind: parameter group: scheduler label: consumer,scheduler type: integer javaType: int optionalPrefix: consumer. deprecated: false secret: false description: The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. backoffMultiplier: kind: parameter group: scheduler label: consumer,scheduler type: integer javaType: int optionalPrefix: consumer. deprecated: false secret: false description: 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: kind: parameter group: scheduler label: consumer,scheduler type: integer javaType: long optionalPrefix: consumer. deprecated: false secret: false defaultValue: "500" description: 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: kind: parameter group: scheduler label: consumer,scheduler type: boolean javaType: boolean optionalPrefix: consumer. deprecated: false secret: false defaultValue: false description: If greedy is enabled then the ScheduledPollConsumer will run immediately again if the previous run polled 1 or more messages. initialDelay: kind: parameter group: scheduler label: consumer,scheduler type: integer javaType: long optionalPrefix: consumer. deprecated: false secret: false defaultValue: "1000" description: 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: kind: parameter group: scheduler label: consumer,scheduler type: string javaType: org.apache.camel.LoggingLevel enum: - TRACE - DEBUG - INFO - WARN - ERROR - OFF optionalPrefix: consumer. deprecated: false secret: false defaultValue: TRACE description: The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. scheduledExecutorService: kind: parameter group: scheduler label: consumer,scheduler type: object javaType: java.util.concurrent.ScheduledExecutorService optionalPrefix: consumer. deprecated: false secret: false description: 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: kind: parameter group: scheduler label: consumer,scheduler type: string javaType: org.apache.camel.spi.ScheduledPollConsumerScheduler enum: - none - spring - quartz2 optionalPrefix: consumer. deprecated: false secret: false defaultValue: none description: To use a cron scheduler from either camel-spring or camel-quartz2 component schedulerProperties: kind: parameter group: scheduler label: consumer,scheduler type: object javaType: java.util.Map prefix: scheduler. multiValue: true deprecated: false secret: false description: To configure additional properties when using a custom scheduler or any of the Quartz2 Spring based scheduler. startScheduler: kind: parameter group: scheduler label: consumer,scheduler type: boolean javaType: boolean optionalPrefix: consumer. deprecated: false secret: false defaultValue: true description: Whether the scheduler should be auto started. timeUnit: kind: parameter group: scheduler label: consumer,scheduler type: string javaType: java.util.concurrent.TimeUnit enum: - NANOSECONDS - MICROSECONDS - MILLISECONDS - SECONDS - MINUTES - HOURS - DAYS optionalPrefix: consumer. deprecated: false secret: false defaultValue: MILLISECONDS description: Time unit for initialDelay and delay options. useFixedDelay: kind: parameter group: scheduler label: consumer,scheduler type: boolean javaType: boolean optionalPrefix: consumer. deprecated: false secret: false defaultValue: true description: Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. documentation.adoc: |+ [[MyBatis-MyBatis]] MyBatis ~~~~~~~ *Available as of Camel 2.7* The *mybatis:* component allows you to query, poll, insert, update and delete data in a relational database using http://mybatis.org/[MyBatis]. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-mybatis x.x.x ------------------------------------------------------------ [[MyBatis-URIformat]] URI format ^^^^^^^^^^ [source,java] ------------------------------- 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. [[MyBatis-Options]] Options ^^^^^^^ // component options: START The MyBatis component supports 2 options which are listed below. {% raw %} [width="100%",cols="2,1m,7",options="header"] |======================================================================= | Name | Java Type | Description | sqlSessionFactory | SqlSessionFactory | To use the SqlSessionFactory | configurationUri | String | Location of MyBatis xml configuration file. The default value is: SqlMapConfig.xml loaded from the classpath |======================================================================= {% endraw %} // component options: END // endpoint options: START The MyBatis component supports 29 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 MyBatis XML mapping file which maps to the query insert update or delete operation you wish to evaluate. | outputHeader | common | | String | Store the query result in a header instead of the message body. By default outputHeader == null and the query result is stored in the message body any existing content in the message body is discarded. If outputHeader is set the value is used as the name of the header to store the query result and the original message body is preserved. Setting outputHeader will also omit populating the default CamelMyBatisResult header since it would be the same as outputHeader all the time. | 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. | inputHeader | consumer | | String | User the header value for input parameters instead of the message body. By default inputHeader == null and the input parameters are taken from the message body. If outputHeader is set the value is used and query parameters will be taken from the header instead of the body. | 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. | transacted | consumer | false | boolean | Enables or disables transaction. If enabled then if processing an exchange failed then the consumer break out processing any further exchanges to cause a rollback eager | 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. | executorType | producer | SIMPLE | ExecutorType | The executor type to be used while executing statements. simple - executor does nothing special. reuse - executor reuses prepared statements. batch - executor reuses statements and batches updates. | 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 [[MyBatis-MessageHeaders]] Message Headers ^^^^^^^^^^^^^^^ Camel will populate the result message, either IN or OUT with a header with the statement used: [width="100%",cols="10%,10%,80%",options="header",] |======================================================================= |Header |Type |Description |`CamelMyBatisStatementName` |`String` |The *statementName* used (for example: insertAccount). |`CamelMyBatisResult` |`Object` |The *response* returned from MtBatis in any of the operations. For instance an `INSERT` could return the auto-generated key, or number of rows etc. |======================================================================= [[MyBatis-MessageBody]] 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 always stored in the header with the key `CamelMyBatisResult`. [[MyBatis-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("mybatis:insertAccount?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: [source,xml] ------------------------------------------------------------ insert into ACCOUNT ( ACC_ID, ACC_FIRST_NAME, ACC_LAST_NAME, ACC_EMAIL ) values ( #{id}, #{firstName}, #{lastName}, #{emailAddress} ) ------------------------------------------------------------ [[MyBatis-UsingStatementTypeforbettercontrolofMyBatis]] 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: 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`: And the same for `UPDATE`, where we can send an `Account` object as the IN body to MyBatis: [[MyBatis-UsingInsertListStatementType]] Using InsertList StatementType ++++++++++++++++++++++++++++++ *Available as of Camel 2.10* MyBatis allows you to insert multiple rows using its for-each batch driver. To use this, you need to use the in the mapper XML file. For example as shown below: Then you can insert multiple rows, by sending a Camel message to the `mybatis` endpoint which uses the `InsertList` statement type, as shown below: [[MyBatis-UsingUpdateListStatementType]] Using UpdateList StatementType ++++++++++++++++++++++++++++++ *Available as of Camel 2.11* MyBatis allows you to update multiple rows using its for-each batch driver. To use this, you need to use the in the mapper XML file. For example as shown below: [source,xml] ------------------------------------------------------------------------------- update ACCOUNT set ACC_EMAIL = #{emailAddress} where ACC_ID in #{Account.id} ------------------------------------------------------------------------------- Then you can update multiple rows, by sending a Camel message to the mybatis endpoint which uses the UpdateList statement type, as shown below: [source,java] -------------------------------------------------------------- from("direct:start") .to("mybatis:batchUpdateAccount?statementType=UpdateList") .to("mock:result"); -------------------------------------------------------------- [[MyBatis-UsingDeleteListStatementType]] Using DeleteList StatementType ++++++++++++++++++++++++++++++ *Available as of Camel 2.11* MyBatis allows you to delete multiple rows using its for-each batch driver. To use this, you need to use the in the mapper XML file. For example as shown below: [source,xml] --------------------------------------------------------------------------------- delete from ACCOUNT where ACC_ID in #{AccountID} --------------------------------------------------------------------------------- Then you can delete multiple rows, by sending a Camel message to the mybatis endpoint which uses the DeleteList statement type, as shown below: [source,java] -------------------------------------------------------------- from("direct:start") .to("mybatis:batchDeleteAccount?statementType=DeleteList") .to("mock:result"); -------------------------------------------------------------- [[MyBatis-NoticeonInsertList,UpdateListandDeleteListStatementTypes]] 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 http://www.mybatis.org/core/dynamic-sql.html[mybatis dynamic queries] capabilities. [[MyBatis-Scheduledpollingexample]] Scheduled polling example +++++++++++++++++++++++++ This component supports scheduled polling and can therefore be used as a??link:polling-consumer.html[Polling Consumer]. For example to poll the database every minute: [source,java] ------------------------------------------------------------------------------- from("mybatis:selectAllAccounts?delay=60000").to("activemq:queue:allAccounts"); ------------------------------------------------------------------------------- See "ScheduledPollConsumer Options" on??link:polling-consumer.html[Polling Consumer] for more options. Alternatively you can 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("mybatis:selectAllAccounts").to("activemq:queue:allAccounts"); ------------------------------------------------------------------------------------------------------------- And the MyBatis SQL mapping file used: [source,xml] ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- [[MyBatis-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 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 processed, so we avoid consuming it twice or more. And the statements in the sqlmap file: [[MyBatis-Participatingintransactions]] 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). [source,xml] ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ 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`: [source,xml] -------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- A http://www.mybatis.org/spring/index.html[mybatis-spring] http://www.mybatis.org/spring/factorybean.html[`SqlSessionFactoryBean`] then wraps that same `DataSource`: [source,xml] ----------------------------------------------------------------------------------- ----------------------------------------------------------------------------------- The camel-mybatis component is then configured with that factory: [source,xml] ----------------------------------------------------------------------------------- ----------------------------------------------------------------------------------- Finally, a link:transactional-client.html[transaction policy] is defined over the top of the transaction manager, which can then be used as usual: [source,xml] ------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------ [[MyBatis-SeeAlso]] See Also ^^^^^^^^ * link:configuring-camel.html[Configuring Camel] * link:component.html[Component] * link:endpoint.html[Endpoint] * link:getting-started.html[Getting Started]