This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/camel.git
commit cc1d44c122aa3cbbf62e410ff092a67a6e1c0c48 Author: Claus Ibsen <claus.ib...@gmail.com> AuthorDate: Wed Mar 28 19:43:44 2018 +0200 CAMEL-12285: Added mybatis-bean as component to use MyBatis annotation mapper. --- .../src/main/docs/mybatis-component.adoc | 192 ++++++++++----------- .../component/mybatis/BaseMyBatisEndpoint.java | 106 ++---------- .../component/mybatis/MyBatisBeanEndpoint.java | 3 +- .../component/mybatis/MyBatisBeanProducer.java | 87 +++++++--- .../camel/component/mybatis/MyBatisEndpoint.java | 82 +++++++++ .../camel/component/mybatis/MyBatisInsertTest.java | 4 + .../component/mybatis/MyBatisTestSupport.java | 2 +- .../component/mybatis/bean/AccountService.java | 6 + .../MyBatisBeanInsertTest.java} | 15 +- .../mybatis/bean/MyBatisBeanSelectOneTest.java | 18 ++ ...> MyBatisBeanSelectOneWithInputHeaderTest.java} | 21 ++- ... MyBatisBeanSelectOneWithOutputHeaderTest.java} | 18 +- 12 files changed, 314 insertions(+), 240 deletions(-) diff --git a/components/camel-mybatis/src/main/docs/mybatis-component.adoc b/components/camel-mybatis/src/main/docs/mybatis-component.adoc index 2ed8a08..2cfc420 100644 --- a/components/camel-mybatis/src/main/docs/mybatis-component.adoc +++ b/components/camel-mybatis/src/main/docs/mybatis-component.adoc @@ -10,21 +10,21 @@ 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-mybatis</artifactId> <version>x.x.x</version> <!-- use the same version as your Camel core version --> </dependency> ------------------------------------------------------------- +---- -### URI format +=== URI format -[source,java] -------------------------------- +[source,text] +---- 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 @@ -39,10 +39,7 @@ the root of the classpath with the expected name of If the file is located in another location, you will need to configure the `configurationUri` option on the `MyBatisComponent` component. -### Options - - - +=== Options // component options: START The MyBatis component supports 3 options which are listed below. @@ -59,10 +56,6 @@ The MyBatis component supports 3 options which are listed below. // component options: END - - - - // endpoint options: START The MyBatis endpoint is configured using URI syntax: @@ -88,9 +81,7 @@ with the following path and query parameters: [width="100%",cols="2,5,^1,2",options="header"] |=== | Name | Description | Default | Type -| *outputHeader* (common) | 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 outputH [...] | *bridgeErrorHandler* (consumer) | 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 or ERROR level and ignored. | false | boolean -| *inputHeader* (consumer) | 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. | | String | *maxMessagesPerPoll* (consumer) | 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. | 0 | int | *onConsume* (consumer) | Statement to run after data has been processed in the route | | String | *routeEmptyResultSet* (consumer) | Whether allow empty resultset to be routed to the next hop | false | boolean @@ -102,6 +93,8 @@ with the following path and query parameters: | *pollStrategy* (consumer) | 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. | | PollingConsumerPoll Strategy | *processingStrategy* (consumer) | To use a custom MyBatisProcessingStrategy | | MyBatisProcessing Strategy | *executorType* (producer) | 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. | SIMPLE | ExecutorType +| *inputHeader* (producer) | 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. | | String +| *outputHeader* (producer) | 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 outpu [...] | *statementType* (producer) | Mandatory to specify for the producer to control which kind of operation to invoke. | | StatementType | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *backoffErrorThreshold* (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | | int @@ -122,7 +115,7 @@ with the following path and query parameters: -### Message Headers +=== Message Headers Camel will populate the result message, either IN or OUT with a header with the statement used: @@ -138,7 +131,7 @@ instance an `INSERT` could return the auto-generated key, or number of rows etc. |======================================================================= -### Message Body +=== 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 @@ -146,16 +139,16 @@ 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`. -### 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"); ---------------------------------------------------- +---- +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. @@ -163,7 +156,7 @@ Camel which kind of operation to invoke. Where *insertAccount* is the MyBatis ID in the SQL mapping file: [source,xml] ------------------------------------------------------------- +---- <!-- Insert example, using the Account parameter class --> <insert id="insertAccount" parameterType="Account"> insert into ACCOUNT ( @@ -176,9 +169,9 @@ Where *insertAccount* is the MyBatis ID in the SQL mapping file: #{id}, #{firstName}, #{lastName}, #{emailAddress} ) </insert> ------------------------------------------------------------- +---- -### Using StatementType for better control of MyBatis +=== 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 @@ -196,7 +189,7 @@ We can do the same for some of the other operations, such as And the same for `UPDATE`, where we can send an `Account` object as the IN body to MyBatis: -#### Using InsertList StatementType +==== Using InsertList StatementType *Available as of Camel 2.10* @@ -208,7 +201,7 @@ Then you can insert multiple rows, by sending a Camel message to the `mybatis` endpoint which uses the `InsertList` statement type, as shown below: -#### Using UpdateList StatementType +==== Using UpdateList StatementType *Available as of Camel 2.11* @@ -217,7 +210,7 @@ driver. To use this, you need to use the <foreach> in the mapper XML file. For example as shown below: [source,xml] -------------------------------------------------------------------------------- +---- <update id="batchUpdateAccount" parameterType="java.util.Map"> update ACCOUNT set ACC_EMAIL = #{emailAddress} @@ -227,20 +220,20 @@ file. For example as shown below: #{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: [source,java] --------------------------------------------------------------- +---- from("direct:start") .to("mybatis:batchUpdateAccount?statementType=UpdateList") .to("mock:result"); --------------------------------------------------------------- +---- -#### Using DeleteList StatementType +==== Using DeleteList StatementType *Available as of Camel 2.11* @@ -249,7 +242,7 @@ driver. To use this, you need to use the <foreach> in the mapper XML file. For example as shown below: [source,xml] ---------------------------------------------------------------------------------- +---- <delete id="batchDeleteAccountById" parameterType="java.util.List"> delete from ACCOUNT where @@ -258,36 +251,37 @@ file. For example as shown below: #{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: [source,java] --------------------------------------------------------------- +---- from("direct:start") .to("mybatis:batchDeleteAccount?statementType=DeleteList") .to("mock:result"); --------------------------------------------------------------- +---- -#### Notice on InsertList, UpdateList and DeleteList StatementTypes +==== 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. -#### Scheduled polling example +==== 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: [source,java] -------------------------------------------------------------------------------- -from("mybatis:selectAllAccounts?delay=60000").to("activemq:queue:allAccounts"); -------------------------------------------------------------------------------- +---- +from("mybatis:selectAllAccounts?delay=60000") + .to("activemq:queue:allAccounts"); +---- See "ScheduledPollConsumer Options" on Polling Consumer for more options. @@ -299,21 +293,23 @@ using the <<timer-component,Timer>> component and send the data to the JMS queue: [source,java] -------------------------------------------------------------------------------------------------------------- -from("timer://pollTheDatabase?delay=30000").to("mybatis:selectAllAccounts").to("activemq:queue:allAccounts"); -------------------------------------------------------------------------------------------------------------- +---- +from("timer://pollTheDatabase?delay=30000") + .to("mybatis:selectAllAccounts") + .to("activemq:queue:allAccounts"); +---- And the MyBatis SQL mapping file used: [source,xml] ----------------------------------------------------------------------------- +---- <!-- Select with no parameters using the result map for Account class. --> <select id="selectAllAccounts" resultMap="AccountResult"> select * from ACCOUNT </select> ----------------------------------------------------------------------------- +---- -#### Using onConsume +==== Using onConsume This component supports executing statements *after* data have been consumed and processed by Camel. This allows you to do post updates in @@ -327,7 +323,7 @@ database to processed, so we avoid consuming it twice or more. And the statements in the sqlmap file: -#### Participating in transactions +==== 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 @@ -340,18 +336,18 @@ participate in Spring transactions (the MyBatis `SqlSessionFactory` does just this). [source,xml] ------------------------------------------------------------------------------------------------------- - <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="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. @@ -360,59 +356,53 @@ A transaction manager is then configured to manage the outermost `DataSource`: [source,xml] --------------------------------------------------------------------------------------------------- - <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> - <property name="dataSource" ref="dataSource"/> - </bean> --------------------------------------------------------------------------------------------------- +---- +<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> + <property name="dataSource" ref="dataSource"/> +</bean> +---- 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] ------------------------------------------------------------------------------------ - <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> ------------------------------------------------------------------------------------ +---- +<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: [source,xml] ------------------------------------------------------------------------------------ - <bean id="mybatis" class="org.apache.camel.component.mybatis.MyBatisComponent"> - <property name="sqlSessionFactory" ref="sqlSessionFactory"/> - </bean> ------------------------------------------------------------------------------------ +---- +<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: [source,xml] ------------------------------------------------------------------------------------------------- - <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> ------------------------------------------------------------------------------------------------- - -### See Also - -* Configuring Camel -* Component -* Endpoint -* Getting Started +---- +<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> +---- + diff --git a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/BaseMyBatisEndpoint.java b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/BaseMyBatisEndpoint.java index 77ae5de..25abb5f 100644 --- a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/BaseMyBatisEndpoint.java +++ b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/BaseMyBatisEndpoint.java @@ -25,25 +25,12 @@ import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSessionFactory; public abstract class BaseMyBatisEndpoint extends DefaultPollingEndpoint { - @UriParam(label = "consumer", 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.") - private boolean transacted; - @UriParam(label = "consumer", defaultValue = "0") - private int maxMessagesPerPoll; - @UriParam - private String outputHeader; - @UriParam(label = "consumer") - private String inputHeader; - @UriParam(label = "consumer", optionalPrefix = "consumer.") - private String onConsume; - @UriParam(label = "consumer", optionalPrefix = "consumer.", defaultValue = "true") - private boolean useIterator = true; - @UriParam(label = "consumer", optionalPrefix = "consumer.") - private boolean routeEmptyResultSet; - @UriParam(label = "consumer,advanced") - private MyBatisProcessingStrategy processingStrategy = new DefaultMyBatisProcessingStrategy(); @UriParam(label = "producer", defaultValue = "SIMPLE") private ExecutorType executorType; + @UriParam(label = "producer") + private String inputHeader; + @UriParam(label = "producer") + private String outputHeader; public BaseMyBatisEndpoint() { } @@ -85,41 +72,18 @@ public abstract class BaseMyBatisEndpoint extends DefaultPollingEndpoint { this.executorType = ExecutorType.valueOf(executorType.toUpperCase()); } - public boolean isTransacted() { - return transacted; - } - - /** - * 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 - */ - public void setTransacted(boolean transacted) { - this.transacted = transacted; - } - - public MyBatisProcessingStrategy getProcessingStrategy() { - return processingStrategy; - } - - /** - * To use a custom MyBatisProcessingStrategy - */ - public void setProcessingStrategy(MyBatisProcessingStrategy processingStrategy) { - this.processingStrategy = processingStrategy; - } - - public int getMaxMessagesPerPoll() { - return maxMessagesPerPoll; + public String getInputHeader() { + return inputHeader; } /** - * 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. + * 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. */ - public void setMaxMessagesPerPoll(int maxMessagesPerPoll) { - this.maxMessagesPerPoll = maxMessagesPerPoll; + public void setInputHeader(String inputHeader) { + this.inputHeader = inputHeader; } public String getOutputHeader() { @@ -139,50 +103,4 @@ public abstract class BaseMyBatisEndpoint extends DefaultPollingEndpoint { this.outputHeader = outputHeader; } - public String getInputHeader() { - return inputHeader; - } - - /** - * 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. - */ - public void setInputHeader(String inputHeader) { - this.inputHeader = inputHeader; - } - - public String getOnConsume() { - return onConsume; - } - - /** - * Statement to run after data has been processed in the route - */ - public void setOnConsume(String onConsume) { - this.onConsume = onConsume; - } - - public boolean isUseIterator() { - return useIterator; - } - - /** - * Process resultset individually or as a list - */ - public void setUseIterator(boolean useIterator) { - this.useIterator = useIterator; - } - - public boolean isRouteEmptyResultSet() { - return routeEmptyResultSet; - } - - /** - * Whether allow empty resultset to be routed to the next hop - */ - public void setRouteEmptyResultSet(boolean routeEmptyResultSet) { - this.routeEmptyResultSet = routeEmptyResultSet; - } } diff --git a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanEndpoint.java b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanEndpoint.java index 09a94cd6..b41ddee 100644 --- a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanEndpoint.java +++ b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanEndpoint.java @@ -22,7 +22,6 @@ import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriEndpoint; -import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; /** @@ -33,7 +32,7 @@ public class MyBatisBeanEndpoint extends BaseMyBatisEndpoint { @UriPath @Metadata(required = "true") private String beanName; - @UriParam(label = "producer") + @UriPath @Metadata(required = "true") private String methodName; public MyBatisBeanEndpoint() { diff --git a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanProducer.java b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanProducer.java index 31ca99c..0bdf76c 100644 --- a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanProducer.java +++ b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanProducer.java @@ -19,8 +19,7 @@ package org.apache.camel.component.mybatis; import org.apache.camel.Exchange; import org.apache.camel.component.bean.BeanProcessor; import org.apache.camel.impl.DefaultProducer; -import org.apache.camel.util.IOHelper; -import org.apache.camel.util.ServiceHelper; +import org.apache.camel.util.ExchangeHelper; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; @@ -29,9 +28,7 @@ import org.slf4j.LoggerFactory; public class MyBatisBeanProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(MyBatisBeanProducer.class); - private MyBatisBeanEndpoint endpoint; - private BeanProcessor beanProcessor; - private SqlSession session; + private final MyBatisBeanEndpoint endpoint; public MyBatisBeanProducer(MyBatisBeanEndpoint endpoint) { super(endpoint); @@ -39,16 +36,7 @@ public class MyBatisBeanProducer extends DefaultProducer { } public void process(Exchange exchange) throws Exception { - LOG.trace("Invoking MyBatisBean on {}:{}", endpoint.getBeanName(), endpoint.getMethodName()); - beanProcessor.process(exchange); - } - - @Override - protected void doStart() throws Exception { - super.doStart(); - - // discover the bean and get the mapper - session = null; + SqlSession session; ExecutorType executorType = endpoint.getExecutorType(); if (executorType == null) { @@ -58,6 +46,52 @@ public class MyBatisBeanProducer extends DefaultProducer { } LOG.debug("Opened MyBatis SqlSession: {}", session); + try { + doProcess(exchange, session); + // flush the batch statements and commit the database connection + session.commit(); + } catch (Exception e) { + // discard the pending batch statements and roll the database connection back + session.rollback(); + throw e; + } finally { + // and finally close the session as we're done + LOG.debug("Closing MyBatis SqlSession: {}", session); + session.close(); + } + } + + protected void doProcess(Exchange exchange, SqlSession session) throws Exception { + LOG.trace("Invoking MyBatisBean on {}:{}", endpoint.getBeanName(), endpoint.getMethodName()); + + // if we use input or output header we need to copy exchange to avoid mutating the + Exchange copy = ExchangeHelper.createCopy(exchange, true); + + Object input = getInput(copy); + copy.getMessage().setBody(input); + + BeanProcessor beanProcessor = createBeanProcessor(session); + beanProcessor.start(); + beanProcessor.process(copy); + beanProcessor.stop(); + + Object result = copy.getMessage().getBody(); + if (result != input) { + if (endpoint.getOutputHeader() != null) { + // set the result as header for insert + LOG.trace("Setting result as header [{}]: {}", endpoint.getOutputHeader(), result); + exchange.getMessage().setHeader(endpoint.getOutputHeader(), result); + } else { + // set the result as body for insert + LOG.trace("Setting result as body: {}", result); + exchange.getMessage().setBody(result); + exchange.getMessage().setHeader(MyBatisConstants.MYBATIS_RESULT, result); + } + } + } + + private BeanProcessor createBeanProcessor(SqlSession session) throws Exception { + // discover the bean and get the mapper // is the bean a alias type Class clazz = session.getConfiguration().getTypeAliasRegistry().resolveAlias(endpoint.getBeanName()); if (clazz == null) { @@ -74,19 +108,18 @@ public class MyBatisBeanProducer extends DefaultProducer { } LOG.debug("Resolved MyBatis Bean mapper: {}", mapper); - beanProcessor = new BeanProcessor(mapper, getEndpoint().getCamelContext()); - beanProcessor.setMethod(endpoint.getMethodName()); - ServiceHelper.startService(beanProcessor); + BeanProcessor answer = new BeanProcessor(mapper, getEndpoint().getCamelContext()); + answer.setMethod(endpoint.getMethodName()); + return answer; } - @Override - protected void doStop() throws Exception { - super.doStop(); - - ServiceHelper.stopService(beanProcessor); - - LOG.debug("Closing MyBatis SqlSession: {}", session); - IOHelper.close(session); - session = null; + private Object getInput(final Exchange exchange) { + final String inputHeader = endpoint.getInputHeader(); + if (inputHeader != null) { + return exchange.getIn().getHeader(inputHeader); + } else { + return exchange.getIn().getBody(); + } } + } diff --git a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisEndpoint.java b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisEndpoint.java index 418c6e9..ca7dcc5 100644 --- a/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisEndpoint.java +++ b/components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisEndpoint.java @@ -41,6 +41,19 @@ public class MyBatisEndpoint extends BaseMyBatisEndpoint { private String statement; @UriParam(label = "producer") private StatementType statementType; + @UriParam(label = "consumer", 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.") + private boolean transacted; + @UriParam(label = "consumer", defaultValue = "0") + private int maxMessagesPerPoll; + @UriParam(label = "consumer", optionalPrefix = "consumer.") + private String onConsume; + @UriParam(label = "consumer", optionalPrefix = "consumer.", defaultValue = "true") + private boolean useIterator = true; + @UriParam(label = "consumer", optionalPrefix = "consumer.") + private boolean routeEmptyResultSet; + @UriParam(label = "consumer,advanced") + private MyBatisProcessingStrategy processingStrategy = new DefaultMyBatisProcessingStrategy(); public MyBatisEndpoint() { } @@ -89,4 +102,73 @@ public class MyBatisEndpoint extends BaseMyBatisEndpoint { this.statementType = statementType; } + public boolean isTransacted() { + return transacted; + } + + /** + * 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 + */ + public void setTransacted(boolean transacted) { + this.transacted = transacted; + } + + public MyBatisProcessingStrategy getProcessingStrategy() { + return processingStrategy; + } + + /** + * To use a custom MyBatisProcessingStrategy + */ + public void setProcessingStrategy(MyBatisProcessingStrategy processingStrategy) { + this.processingStrategy = processingStrategy; + } + + public int getMaxMessagesPerPoll() { + return maxMessagesPerPoll; + } + + /** + * 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. + */ + public void setMaxMessagesPerPoll(int maxMessagesPerPoll) { + this.maxMessagesPerPoll = maxMessagesPerPoll; + } + + public String getOnConsume() { + return onConsume; + } + + /** + * Statement to run after data has been processed in the route + */ + public void setOnConsume(String onConsume) { + this.onConsume = onConsume; + } + + public boolean isUseIterator() { + return useIterator; + } + + /** + * Process resultset individually or as a list + */ + public void setUseIterator(boolean useIterator) { + this.useIterator = useIterator; + } + + public boolean isRouteEmptyResultSet() { + return routeEmptyResultSet; + } + + /** + * Whether allow empty resultset to be routed to the next hop + */ + public void setRouteEmptyResultSet(boolean routeEmptyResultSet) { + this.routeEmptyResultSet = routeEmptyResultSet; + } } diff --git a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertTest.java b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertTest.java index ff365a1..61a9520 100644 --- a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertTest.java +++ b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertTest.java @@ -16,6 +16,10 @@ */ package org.apache.camel.component.mybatis; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; + import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Test; diff --git a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisTestSupport.java b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisTestSupport.java index 9234193..b9caf9b 100644 --- a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisTestSupport.java +++ b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisTestSupport.java @@ -77,7 +77,7 @@ public abstract class MyBatisTestSupport extends CamelTestSupport { super.tearDown(); } - private Connection createConnection() throws Exception { + protected Connection createConnection() throws Exception { MyBatisComponent component = context.getComponent("mybatis", MyBatisComponent.class); return component.createSqlSessionFactory().getConfiguration().getEnvironment().getDataSource().getConnection(); } diff --git a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/AccountService.java b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/AccountService.java index ec3320a..ded378d 100644 --- a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/AccountService.java +++ b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/AccountService.java @@ -19,6 +19,7 @@ package org.apache.camel.component.mybatis.bean; import java.util.List; import org.apache.camel.component.mybatis.Account; +import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.Select; @@ -32,4 +33,9 @@ public interface AccountService { @Select("select * from ACCOUNT order by ACC_ID") @ResultMap("Account.AccountResult") List<Account> selectBeanAllAccounts(); + + @Insert("insert into ACCOUNT (ACC_ID,ACC_FIRST_NAME,ACC_LAST_NAME,ACC_EMAIL)" + + " values (#{id}, #{firstName}, #{lastName}, #{emailAddress})") + void insertBeanAccount(Account account); + } diff --git a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertTest.java b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanInsertTest.java similarity index 83% copy from components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertTest.java copy to components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanInsertTest.java index ff365a1..7950024 100644 --- a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisInsertTest.java +++ b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanInsertTest.java @@ -5,22 +5,24 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.camel.component.mybatis; +package org.apache.camel.component.mybatis.bean; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.component.mybatis.Account; +import org.apache.camel.component.mybatis.MyBatisTestSupport; import org.junit.Test; -public class MyBatisInsertTest extends MyBatisTestSupport { +public class MyBatisBeanInsertTest extends MyBatisTestSupport { @Test public void testInsert() throws Exception { @@ -48,10 +50,11 @@ public class MyBatisInsertTest extends MyBatisTestSupport { @Override public void configure() throws Exception { from("direct:start") - .to("mybatis:insertAccount?statementType=Insert") + .to("mybatis-bean:AccountService:insertBeanAccount") .to("mock:result"); } }; } + } diff --git a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java index bdb4025..4297eae 100644 --- a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java +++ b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java @@ -38,6 +38,24 @@ public class MyBatisBeanSelectOneTest extends MyBatisTestSupport { assertEquals("Claus", account.getFirstName()); } + @Test + public void testSelectOneTwoTime() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedMessageCount(2); + mock.message(0).body().isInstanceOf(Account.class); + mock.message(1).body().isInstanceOf(Account.class); + + template.sendBody("direct:start", 456); + template.sendBody("direct:start", 123); + + assertMockEndpointsSatisfied(); + + Account account = mock.getReceivedExchanges().get(0).getIn().getBody(Account.class); + assertEquals("Claus", account.getFirstName()); + account = mock.getReceivedExchanges().get(1).getIn().getBody(Account.class); + assertEquals("James", account.getFirstName()); + } + @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { diff --git a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneWithInputHeaderTest.java similarity index 70% copy from components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java copy to components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneWithInputHeaderTest.java index bdb4025..dcae3a8 100644 --- a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java +++ b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneWithInputHeaderTest.java @@ -22,7 +22,11 @@ import org.apache.camel.component.mybatis.Account; import org.apache.camel.component.mybatis.MyBatisTestSupport; import org.junit.Test; -public class MyBatisBeanSelectOneTest extends MyBatisTestSupport { +public class MyBatisBeanSelectOneWithInputHeaderTest extends MyBatisTestSupport { + + private static final String TEST_CASE_HEADER_NAME = "testCaseHeader"; + private static final int TEST_ACCOUNT_ID = 456; + private static final int TEST_ACCOUNT_ID_BAD = 999; @Test public void testSelectOne() throws Exception { @@ -30,7 +34,7 @@ public class MyBatisBeanSelectOneTest extends MyBatisTestSupport { mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(Account.class); - template.sendBody("direct:start", 456); + template.sendBodyAndHeader("direct:start", TEST_ACCOUNT_ID_BAD, TEST_CASE_HEADER_NAME, TEST_ACCOUNT_ID); assertMockEndpointsSatisfied(); @@ -38,13 +42,24 @@ public class MyBatisBeanSelectOneTest extends MyBatisTestSupport { assertEquals("Claus", account.getFirstName()); } + @Test + public void tesSelectOneNotFound() throws Exception { + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedMessageCount(1); + mock.message(0).body().isNull(); + + template.sendBodyAndHeader("direct:start", TEST_ACCOUNT_ID, TEST_CASE_HEADER_NAME, TEST_ACCOUNT_ID_BAD); + + assertMockEndpointsSatisfied(); + } + @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") - .to("mybatis-bean:AccountService:selectBeanAccountById") + .to("mybatis-bean:AccountService:selectBeanAccountById?inputHeader=" + TEST_CASE_HEADER_NAME) .to("mock:result"); } }; diff --git a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneWithOutputHeaderTest.java similarity index 70% copy from components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java copy to components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneWithOutputHeaderTest.java index bdb4025..b97bde9 100644 --- a/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java +++ b/components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneWithOutputHeaderTest.java @@ -19,22 +19,28 @@ package org.apache.camel.component.mybatis.bean; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.component.mybatis.Account; +import org.apache.camel.component.mybatis.MyBatisConstants; import org.apache.camel.component.mybatis.MyBatisTestSupport; import org.junit.Test; -public class MyBatisBeanSelectOneTest extends MyBatisTestSupport { +public class MyBatisBeanSelectOneWithOutputHeaderTest extends MyBatisTestSupport { + + private static final String TEST_CASE_HEADER_NAME = "testCaseHeader"; + private static final int TEST_ACCOUNT_ID = 456; @Test - public void testSelectOne() throws Exception { + public void testSelectOneWithOutputHeader() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); - mock.message(0).body().isInstanceOf(Account.class); + mock.message(0).header(TEST_CASE_HEADER_NAME).isInstanceOf(Account.class); + mock.message(0).body().isEqualTo(TEST_ACCOUNT_ID); + mock.message(0).header(MyBatisConstants.MYBATIS_RESULT).isNull(); - template.sendBody("direct:start", 456); + template.sendBody("direct:start", TEST_ACCOUNT_ID); assertMockEndpointsSatisfied(); - Account account = mock.getReceivedExchanges().get(0).getIn().getBody(Account.class); + Account account = mock.getReceivedExchanges().get(0).getIn().getHeader(TEST_CASE_HEADER_NAME, Account.class); assertEquals("Claus", account.getFirstName()); } @@ -44,7 +50,7 @@ public class MyBatisBeanSelectOneTest extends MyBatisTestSupport { @Override public void configure() throws Exception { from("direct:start") - .to("mybatis-bean:AccountService:selectBeanAccountById") + .to("mybatis-bean:AccountService:selectBeanAccountById?outputHeader=" + TEST_CASE_HEADER_NAME) .to("mock:result"); } }; -- To stop receiving notification emails like this one, please contact davscl...@apache.org.