camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Zemian Deng (Confluence)" <conflue...@apache.org>
Subject [CONF] Apache Camel > SQL Component
Date Tue, 20 Aug 2013 23:38:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/en/2176/1/1/_/styles/combined.css?spaceKey=CAMEL&amp;forWysiwyg=true" type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CAMEL/SQL+Component">SQL Component</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~saltnlight5">Zemian Deng</a>
    </h4>
        <br/>
                         <h4>Changes (1)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >d) If the query resulted in more than one rows, it throws an non-unique result exception.| <br>| {{outputClass}} | {{String}} | {{null}} | *Camel 2.12.0:* Specify the full package and class name to use as conversion when {{outputType=SelectOne}}. | <br></td></tr>
            <tr><td class="diff-changed-lines" >| {{parametersCount}} | {{int}} | {{0}} | *Camel 2.11.2/2.12.0* If set greater than zero, then Camel will use this count value of parameters to replace instead of querying via JDBC metadata API. This is useful if the JDBC vendor <span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">should incorrectly returns wrong</span> <span class="diff-added-words"style="background-color: #dfd;">could not return correct</span> parameters <span class="diff-changed-words">count<span class="diff-added-chars"style="background-color: #dfd;">, then user may override instead</span>.</span> | <br></td></tr>
            <tr><td class="diff-unchanged" >{div} <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h2><a name="SQLComponent-SQLComponent"></a>SQL Component</h2>

<p>The <b>sql:</b> component allows you to work with databases using JDBC queries. The difference between this component and <a href="/confluence/display/CAMEL/JDBC" title="JDBC">JDBC</a> component is that in case of SQL the query is a property of the endpoint and it uses message payload as parameters passed to the query.</p>

<p>This component uses <tt><b>spring-jdbc</b></tt> behind the scenes for the actual SQL handling.</p>

<p>Maven users will need to add the following dependency to their <tt>pom.xml</tt> for this component:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
&lt;dependency&gt;
    &lt;groupId&gt;org.apache.camel&lt;/groupId&gt;
    &lt;artifactId&gt;camel-sql&lt;/artifactId&gt;
    &lt;version&gt;x.x.x&lt;/version&gt;
    &lt;!-- use the same version as your Camel core version --&gt;
&lt;/dependency&gt;
</pre>
</div></div>

<p>The SQL component also supports:</p>
<ul class="alternate" type="square">
	<li>a JDBC based repository for the <a href="/confluence/display/CAMEL/Idempotent+Consumer" title="Idempotent Consumer">Idempotent Consumer</a> EIP pattern. See further below.</li>
	<li>a JDBC based repository for the <a href="/confluence/display/CAMEL/Aggregator2" title="Aggregator2">Aggregator</a> EIP pattern. See further below.</li>
</ul>


<h3><a name="SQLComponent-URIformat"></a>URI format</h3>

<div class='panelMacro'><table class='warningMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/forbidden.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>In Camel 2.10 or older the SQL component can only be used as producer.<br/>
>From Camel 2.11 onwards this component can also be a consumer, eg <tt>from()</tt>.</td></tr></table></div>

<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>This component can be used as a <a href="http://camel.apache.org/transactional-client.html" class="external-link" rel="nofollow">Transactional Client</a>.</td></tr></table></div>

<p>The SQL component uses the following endpoint URI notation:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
sql:select * from table where id=# order by name[?options]
</pre>
</div></div>

<p>From Camel 2.11 onwards you can use named parameters by using <tt>&#35;:name</tt> style as shown:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
sql:select * from table where id=:#myId order by name[?options]
</pre>
</div></div>

<p>When using named parameters, Camel will lookup the names from, in the given precedence:<br/>
1. from message body if its a <tt>java.util.Map</tt><br/>
2. from message headers</p>

<p>If a named parameter cannot be resolved, then an exception is thrown.</p>

<p>Notice that the standard <tt>?</tt> symbol that denotes the parameters to an SQL query is substituted with the <tt>&#35;</tt> symbol, because the <tt>?</tt> symbol is used to specify options for the endpoint. The <tt>?</tt> symbol replacement can be configured on endpoint basis.</p>

<p>You can append query options to the URI in the following format, <tt>?option=value&amp;option=value&amp;...</tt></p>

<h3><a name="SQLComponent-Options"></a>Options</h3>

<div class="confluenceTableSmall"><div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Option </th>
<th class='confluenceTh'> Type </th>
<th class='confluenceTh'> Default </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>batch</tt> </td>
<td class='confluenceTd'> <tt>boolean</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.7.5, 2.8.4 and 2.9:</b> Execute SQL batch update statements. See notes below on how the treatment of the inbound message body changes if this is set to <tt>true</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>dataSourceRef</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Deprecated and will be removed in Camel 3.0:</b> Reference to a <tt>DataSource</tt> to look up in the registry. Use <tt>dataSource=#theName</tt> instead. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>dataSource</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> Reference to a <tt>DataSource</tt> to look up in the registry. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>placeholder</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>&#35;</tt> </td>
<td class='confluenceTd'> <b>Camel 2.4:</b> Specifies a character that will be replaced to <tt>?</tt> in SQL query. Notice, that it is simple <tt>String.replaceAll()</tt> operation and no SQL parsing is involved (quoted strings will also change). This replacement is <b>only</b> happening if the endpoint is created using the <tt>SqlComponent</tt>. If you manually create the endpoint, then use the expected <tt>?</tt> sign instead. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>template.&lt;xxx&gt;</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> Sets additional options on the Spring <tt>JdbcTemplate</tt> that is used behind the scenes to execute the queries. For instance, <tt>template.maxRows=10</tt>. For detailed documentation, see the <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html" class="external-link" rel="nofollow">JdbcTemplate javadoc</a> documentation. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>allowNamedParameters</tt> </td>
<td class='confluenceTd'> <tt>boolean</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> Whether to allow using named parameters in the queries. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>processingStrategy</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> Allows to plugin to use a custom <tt>org.apache.camel.component.sql.SqlProcessingStrategy</tt> to execute queries when the consumer has processed the rows/batch. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>prepareStatementStrategy</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.11:</b> Allows to plugin to use a custom <tt>org.apache.camel.component.sql.SqlPrepareStatementStrategy</tt> to control preparation of the query and prepared statement. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.delay</tt> </td>
<td class='confluenceTd'> <tt>long</tt> </td>
<td class='confluenceTd'> <tt>500</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> Delay in milliseconds between each poll. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.initialDelay</tt> </td>
<td class='confluenceTd'> <tt>long</tt> </td>
<td class='confluenceTd'> <tt>1000</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> Milliseconds before polling starts. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.useFixedDelay</tt> </td>
<td class='confluenceTd'> <tt>boolean</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> Set to <tt>true</tt> to use fixed delay between polls, otherwise fixed rate is used. See <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html" class="external-link" rel="nofollow">ScheduledExecutorService</a> in JDK for details. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>maxMessagesPerPoll</tt> </td>
<td class='confluenceTd'> <tt>int</tt> </td>
<td class='confluenceTd'> <tt>0</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> An integer value to define the maximum number of messages to gather per poll. By default, no maximum is set. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.useIterator</tt> </td>
<td class='confluenceTd'> <tt>boolean</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> If <tt>true</tt> each row returned when polling will be processed individually. If <tt>false</tt> the entire <tt>java.util.List</tt> of data is set as the IN body. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.routeEmptyResultSet</tt> </td>
<td class='confluenceTd'> <tt>boolean</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> Whether to route a single empty <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> if there was no data to poll. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.onConsume</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> After processing each row then this query can be executed, if the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> was processed successfully, for example to mark the row as processed. The query can have parameter. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.onConsumeFailed</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> After processing each row then this query can be executed, if the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> failed, for example to  mark the row as failed. The query can have parameter. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.onConsumeBatchComplete</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> After processing the entire batch, this query can be executed to bulk update rows etc. The query cannot have parameters. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.expectedUpdateCount</tt> </td>
<td class='confluenceTd'> <tt>int</tt> </td>
<td class='confluenceTd'> <tt>&#45;1</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> If using <tt>consumer.onConsume</tt> then this option can be used to set an expected number of rows being updated. Typically you may set this to <tt>1</tt> to expect one row to be updated. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>consumer.breakBatchOnConsumeFail</tt> </td>
<td class='confluenceTd'> <tt>boolean</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL consumer only:</b> If using <tt>consumer.onConsume</tt> and it fails, then this option controls whether to break out of the batch or continue processing the next row from the batch. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>alwaysPopulateStatement</tt> </td>
<td class='confluenceTd'> <tt>boolean</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> <b>SQL producer only:</b> If enabled then the <tt>populateStatement</tt> method from <tt>org.apache.camel.component.sql.SqlPrepareStatementStrategy</tt> is always invoked, also if there is no expected parameters to be prepared. When this is <tt>false</tt> then the <tt>populateStatement</tt> is only invoked if there is 1 or more expected parameters to be set; for example this avoids reading the message body/headers for SQL queries with no parameters. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>separator</tt> </td>
<td class='confluenceTd'> <tt>char</tt> </td>
<td class='confluenceTd'> <tt>,</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> The separator to use when parameter values is taken from message body (if the body is a String type), to be inserted at # placeholders. Notice if you use named parameters, then a <tt>Map</tt> type is used instead. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>outputType</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>SelectList</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12.0:</b> Make the output of consumer or producer to <tt>SelectList</tt> as List of Map, or <tt>SelectOne</tt> as single Java object in the following way:<br/>
a) If the query has only single column, then that JDBC Column object is returned. (such as <tt>SELECT COUNT( * ) FROM PROJECT</tt> will return a Long object.<br/>
b) If the query has more than one column, then it will return a Map of that result.<br/>
c) If the <tt>outputClass</tt> is set, then it will convert the query result into an Java bean object by calling all the setters that match the column names. It will assume your class has a default constructor to create instance with.<br/>
d) If the query resulted in more than one rows, it throws an non-unique result exception.</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>outputClass</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12.0:</b> Specify the full package and class name to use as conversion when <tt>outputType=SelectOne</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>parametersCount</tt> </td>
<td class='confluenceTd'> <tt>int</tt> </td>
<td class='confluenceTd'> <tt>0</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.2/2.12.0</b> If set greater than zero, then Camel will use this count value of parameters to replace instead of querying via JDBC metadata API. This is useful if the JDBC vendor could not return correct parameters count, then user may override instead. </td>
</tr>
</tbody></table>
</div>
</div>

<h3><a name="SQLComponent-Treatmentofthemessagebody"></a>Treatment of the message body</h3>

<p>The SQL component tries to convert the message body to an object of <tt>java.util.Iterator</tt> type and then uses this iterator to fill the query parameters (where each query parameter is represented by a <tt>&#35;</tt> symbol (or configured placeholder) in the endpoint URI). If the message body is not an array or collection, the conversion results in an iterator that iterates over only one object, which is the body itself.</p>

<p>For example, if the message body is an instance of <tt>java.util.List</tt>, the first item in the list is substituted into the first occurrence of <tt>&#35;</tt> in the SQL query, the second item in the list is substituted into the second occurrence of <tt>&#35;</tt>, and so on.</p>

<p>If <tt>batch</tt> is set to <tt>true</tt>, then the interpretation of the inbound message body changes slightly &#8211; instead of an iterator of parameters, the component expects an iterator that contains the parameter iterators; the size of the outer iterator determines the batch size.</p>

<h3><a name="SQLComponent-Resultofthequery"></a>Result of the query</h3>

<p>For <tt>select</tt> operations, the result is an instance of <tt>List&lt;Map&lt;String, Object&gt;&gt;</tt> type, as returned by the <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html#queryForList(java.lang.String,%20java.lang.Object%91%93)" class="external-link" rel="nofollow">JdbcTemplate.queryForList()</a> method. For <tt>update</tt> operations, the result is the number of updated rows, returned as an <tt>Integer</tt>.</p>

<h3><a name="SQLComponent-Headervalues"></a>Header values</h3>

<p>When performing <tt>update</tt> operations, the SQL Component stores the update count in the following message headers:</p>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Header </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelSqlUpdateCount</tt> </td>
<td class='confluenceTd'> The number of rows updated for <tt>update</tt> operations, returned as an <tt>Integer</tt> object. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelSqlRowCount</tt> </td>
<td class='confluenceTd'> The number of rows returned for <tt>select</tt> operations, returned as an <tt>Integer</tt> object. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelSqlQuery</tt> </td>
<td class='confluenceTd'> <b>Camel 2.8:</b> Query to execute. This query takes precedence over the query specified in the endpoint URI. Note that query parameters in the header <em>are</em> represented by a <tt>?</tt> instead of a <tt>&#35;</tt> symbol </td>
</tr>
</tbody></table>
</div>


<h3><a name="SQLComponent-Configuration"></a>Configuration</h3>

<p>You can now set a reference to a <tt>DataSource</tt> in the URI directly:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
sql:select * from table where id=# order by name?dataSource=myDS
</pre>
</div></div>

<h3><a name="SQLComponent-Sample"></a>Sample</h3>

<p>In the sample below we execute a query and retrieve the result as a <tt>List</tt> of rows, where each row is a <tt>Map&lt;String, Object</tt> and the key is the column name.</p>

<p>First, we set up a table to use for our sample. As this is based on an unit test, we do it in java:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// this is the database we create with some initial data for our unit test
db = new EmbeddedDatabaseBuilder()
    .setType(EmbeddedDatabaseType.DERBY).addScript("sql/createAndPopulateDatabase.sql").build();
]]></script>
</div></div>

<p>The SQL script <tt>createAndPopulateDatabase.sql</tt> we execute looks like as described below:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: sql; gutter: false"><![CDATA[
create table projects (id integer primary key, project varchar(10), license varchar(5));
insert into projects values (1, 'Camel', 'ASF');
insert into projects values (2, 'AMQ', 'ASF');
insert into projects values (3, 'Linux', 'XXX');
]]></script>
</div></div>

<p>Then we configure our route and our <tt>sql</tt> component. Notice that we use a <tt>direct</tt> endpoint in front of the <tt>sql</tt> endpoint. This allows us to send an exchange to the <tt>direct</tt> endpoint with the URI, <tt>direct:simple</tt>, which is much easier for the client to use than the long <tt>sql:</tt> URI. Note that the <tt>DataSource</tt> is looked up up in the registry, so we can use standard Spring XML to configure our <tt>DataSource</tt>.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:simple")
    .to("sql:select * from projects where license = # order by id?dataSourceRef=jdbc/myDataSource")
    .to("mock:result");
]]></script>
</div></div>

<p>And then we fire the message into the <tt>direct</tt> endpoint that will route it to our <tt>sql</tt> component that queries the database.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);

// send the query to direct that will route it to the sql where we will execute the query
// and bind the parameters with the data from the body. The body only contains one value
// in this case (XXX) but if we should use multi values then the body will be iterated
// so we could supply a List&lt;String&gt; instead containing each binding value.
template.sendBody("direct:simple", "XXX");

mock.assertIsSatisfied();

// the result is a List
List&lt;?&gt; received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());

// and each row in the list is a Map
Map&lt;?, ?&gt; row = assertIsInstanceOf(Map.class, received.get(0));

// and we should be able the get the project from the map that should be Linux
assertEquals("Linux", row.get("PROJECT"));
]]></script>
</div></div>

<p>We could configure the <tt>DataSource</tt> in Spring XML as follows:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
 &lt;jee:jndi-lookup id="myDS" jndi-name="jdbc/myDataSource"/&gt;
</pre>
</div></div>

<h4><a name="SQLComponent-Usingnamedparameters"></a>Using named parameters</h4>

<p><b>Available as of Camel 2.11</b></p>

<p>In the given route below, we want to get all the projects from the projects table. Notice the SQL query has 2 named parameters, :#lic and :#min.<br/>
Camel will then lookup for these parameters from the message body or message headers. Notice in the example above we set two headers with constant value<br/>
for the named parameters:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
   from("direct:projects")
     .setHeader("lic", constant("ASF"))
     .setHeader("min", constant(123))
     .to("sql:select * from projects where license = :#lic and id &gt; :#min order by id")
</pre>
</div></div>

<p>Though if the message body is a <tt>java.util.Map</tt> then the named parameters will be taken from the body.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
   from("direct:projects")
     .to("sql:select * from projects where license = :#lic and id &gt; :#min order by id")
</pre>
</div></div>

<h3><a name="SQLComponent-UsingtheJDBCbasedidempotentrepository"></a>Using the JDBC based idempotent repository</h3>

<p><b>Available as of Camel 2.7</b>: In this section we will use the JDBC based idempotent repository.</p>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td><b>Abstract class</b><br />From Camel 2.9 onwards there is an abstract class <tt>org.apache.camel.processor.idempotent.jdbc.AbstractJdbcMessageIdRepository</tt> you can extend to build custom JDBC idempotent repository.</td></tr></table></div>

<p>First we have to create the database table which will be used by the idempotent repository. For <b>Camel 2.7</b>, we use the following schema:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: sql; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
CREATE TABLE CAMEL_MESSAGEPROCESSED (
  processorName VARCHAR(255),
  messageId VARCHAR(100)
)
</pre>
</div></div>

<p>In <b>Camel 2.8</b>, we added the createdAt column:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: sql; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
CREATE TABLE CAMEL_MESSAGEPROCESSED (
  processorName VARCHAR(255),
  messageId VARCHAR(100),
  createdAt TIMESTAMP
)
</pre>
</div></div>

<p>We recommend to have a unique constraint on the columns processorName and messageId. Because the syntax for this constraint differs for database to database, we do not show it here.</p>

<p>Second we need to setup a <tt>javax.sql.DataSource</tt> in the spring XML file:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;jdbc:embedded-database id="dataSource" type="DERBY" /&gt;
]]></script>
</div></div>

<p>And finally we can create our JDBC idempotent repository in the spring XML file as well:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;bean id="messageIdRepository" class="org.apache.camel.processor.idempotent.jdbc.JdbcMessageIdRepository"&gt;
	&lt;constructor-arg ref="dataSource" /&gt;
	&lt;constructor-arg value="myProcessorName" /&gt;
&lt;/bean&gt;

&lt;camel:camelContext&gt;
	&lt;camel:errorHandler id="deadLetterChannel" type="DeadLetterChannel" deadLetterUri="mock:error"&gt;
		&lt;camel:redeliveryPolicy maximumRedeliveries="0" maximumRedeliveryDelay="0" logStackTrace="false" /&gt;
	&lt;/camel:errorHandler&gt;
	
	&lt;camel:route id="JdbcMessageIdRepositoryTest" errorHandlerRef="deadLetterChannel"&gt;
		&lt;camel:from uri="direct:start" /&gt;
		&lt;camel:idempotentConsumer messageIdRepositoryRef="messageIdRepository"&gt;
			&lt;camel:header&gt;messageId&lt;/camel:header&gt;
			&lt;camel:to uri="mock:result" /&gt;
		&lt;/camel:idempotentConsumer&gt;
	&lt;/camel:route&gt;
&lt;/camel:camelContext&gt;
]]></script>
</div></div>

<h4><a name="SQLComponent-CustomizetheJdbcMessageIdRepository"></a>Customize the JdbcMessageIdRepository</h4>

<p>Starting with <b>Camel 2.9.1</b> you have a few options to tune the <tt>org.apache.camel.processor.idempotent.jdbc.JdbcMessageIdRepository</tt> for your needs:</p>
<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Parameter </th>
<th class='confluenceTh'> Default Value </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> createTableIfNotExists </td>
<td class='confluenceTd'> true </td>
<td class='confluenceTd'> Defines whether or not Camel should try to create the table if it doesn't exist. </td>
</tr>
<tr>
<td class='confluenceTd'> tableExistsString </td>
<td class='confluenceTd'> SELECT 1 FROM CAMEL_MESSAGEPROCESSED WHERE 1 = 0 </td>
<td class='confluenceTd'> This query is used to figure out whether the table already exists or not. It must throw an exception to indicate the table doesn't exist. </td>
</tr>
<tr>
<td class='confluenceTd'> createString </td>
<td class='confluenceTd'> CREATE TABLE CAMEL_MESSAGEPROCESSED (processorName VARCHAR(255), messageId VARCHAR(100), createdAt TIMESTAMP) </td>
<td class='confluenceTd'> The statement which is used to create the table. </td>
</tr>
<tr>
<td class='confluenceTd'> queryString </td>
<td class='confluenceTd'> SELECT COUNT&#40;*) FROM CAMEL_MESSAGEPROCESSED WHERE processorName = ? AND messageId = ? </td>
<td class='confluenceTd'> The query which is used to figure out whether the message already exists in the repository (the result is not equals to '0'). It takes two parameters. This first one is the processor name (<tt>String</tt>) and the second one is the message id (<tt>String</tt>). </td>
</tr>
<tr>
<td class='confluenceTd'> insertString </td>
<td class='confluenceTd'> INSERT INTO CAMEL_MESSAGEPROCESSED (processorName, messageId, createdAt) VALUES (?, ?, ?) </td>
<td class='confluenceTd'> The statement which is used to add the entry into the table. It takes three parameter. The first one is the processor name (<tt>String</tt>), the second one is the message id (<tt>String</tt>) and the third one is the timestamp (<tt>java.sql.Timestamp</tt>) when this entry was added to the repository. </td>
</tr>
<tr>
<td class='confluenceTd'> deleteString </td>
<td class='confluenceTd'> DELETE FROM CAMEL_MESSAGEPROCESSED WHERE processorName = ? AND messageId = ? </td>
<td class='confluenceTd'> The statement which is used to delete the entry from the database. It takes two parameter. This first one is the processor name (<tt>String</tt>) and the second one is the message id (<tt>String</tt>). </td>
</tr>
</tbody></table>
</div>


<p>A customized <tt>org.apache.camel.processor.idempotent.jdbc.JdbcMessageIdRepository</tt> could look like:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;bean id="messageIdRepository" class="org.apache.camel.processor.idempotent.jdbc.JdbcMessageIdRepository"&gt;
	&lt;constructor-arg ref="dataSource" /&gt;
	&lt;constructor-arg value="myProcessorName" /&gt;
	&lt;property name="tableExistsString" value="SELECT 1 FROM CUSTOMIZED_MESSAGE_REPOSITORY WHERE 1 = 0" /&gt;
	&lt;property name="createString" value="CREATE TABLE CUSTOMIZED_MESSAGE_REPOSITORY (processorName VARCHAR(255), messageId VARCHAR(100), createdAt TIMESTAMP)" /&gt;
	&lt;property name="queryString" value="SELECT COUNT(*) FROM CUSTOMIZED_MESSAGE_REPOSITORY WHERE processorName = ? AND messageId = ?" /&gt;
	&lt;property name="insertString" value="INSERT INTO CUSTOMIZED_MESSAGE_REPOSITORY (processorName, messageId, createdAt) VALUES (?, ?, ?)" /&gt;
	&lt;property name="deleteString" value="DELETE FROM CUSTOMIZED_MESSAGE_REPOSITORY WHERE processorName = ? AND messageId = ?" /&gt;
&lt;/bean&gt;
]]></script>
</div></div>

<h3><a name="SQLComponent-UsingtheJDBCbasedaggregationrepository"></a>Using the JDBC based aggregation repository</h3>

<p><b>Available as of Camel 2.6</b></p>
<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td><b>Using JdbcAggregationRepository in Camel 2.6</b><br />In Camel 2.6, the JdbcAggregationRepository is provided in the <tt>camel-jdbc-aggregator</tt> component. From Camel 2.7 onwards, the <tt>JdbcAggregationRepository</tt> is provided in the <tt>camel-sql</tt> component.</td></tr></table></div>
<p><tt>JdbcAggregationRepository</tt> is an <tt>AggregationRepository</tt> which on the fly persists the aggregated messages. This ensures that you will not loose messages, as the default aggregator will use an in memory only <tt>AggregationRepository</tt>.<br/>
The <tt>JdbcAggregationRepository</tt> allows together with Camel to provide persistent support for the <a href="/confluence/display/CAMEL/Aggregator2" title="Aggregator2">Aggregator</a>.</p>

<p>It has the following options:</p>
<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Option </th>
<th class='confluenceTh'> Type </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>dataSource</tt> </td>
<td class='confluenceTd'> <tt>DataSource</tt> </td>
<td class='confluenceTd'> <b>Mandatory:</b> The <tt>javax.sql.DataSource</tt> to use for accessing the database. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>repositoryName</tt> </td>
<td class='confluenceTd'> <tt>String</tt> </td>
<td class='confluenceTd'> <b>Mandatory:</b> The name of the repository. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>transactionManager</tt> </td>
<td class='confluenceTd'> <tt>TransactionManager</tt> </td>
<td class='confluenceTd'> <b>Mandatory:</b> The <tt>org.springframework.transaction.PlatformTransactionManager</tt> to mange transactions for the database. The TransactionManager must be able to support databases. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>lobHandler</tt> </td>
<td class='confluenceTd'> <tt>LobHandler</tt> </td>
<td class='confluenceTd'> A <tt>org.springframework.jdbc.support.lob.LobHandler</tt> to handle Lob types in the database. Use this option to use a vendor specific LobHandler, for example when using Oracle. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>returnOldExchange</tt> </td>
<td class='confluenceTd'> boolean </td>
<td class='confluenceTd'> Whether the get operation should return the old existing Exchange if any existed. By default this option is <tt>false</tt> to optimize as we do not need the old exchange when aggregating. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>useRecovery</tt> </td>
<td class='confluenceTd'> boolean </td>
<td class='confluenceTd'> Whether or not recovery is enabled. This option is by default <tt>true</tt>. When enabled the Camel <a href="/confluence/display/CAMEL/Aggregator2" title="Aggregator2">Aggregator</a> automatic recover failed aggregated exchange and have them resubmitted. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>recoveryInterval</tt> </td>
<td class='confluenceTd'> long </td>
<td class='confluenceTd'> If recovery is enabled then a background task is run every x'th time to scan for failed exchanges to recover and resubmit. By default this interval is 5000 millis. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>maximumRedeliveries</tt> </td>
<td class='confluenceTd'> int </td>
<td class='confluenceTd'> Allows you to limit the maximum number of redelivery attempts for a recovered exchange. If enabled then the Exchange will be moved to the dead letter channel if all redelivery attempts failed. By default this option is disabled. If this option is used then the <tt>deadLetterUri</tt> option must also be provided. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>deadLetterUri</tt> </td>
<td class='confluenceTd'> String </td>
<td class='confluenceTd'> An endpoint uri for a <a href="/confluence/display/CAMEL/Dead+Letter+Channel" title="Dead Letter Channel">Dead Letter Channel</a> where exhausted recovered Exchanges will be moved. If this option is used then the <tt>maximumRedeliveries</tt> option must also be provided. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>storeBodyAsText</tt> </td>
<td class='confluenceTd'> boolean </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> Whether to store the message body as String which is human readable. By default this option is <tt>false</tt> storing the body in binary format. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>headersToStoreAsText</tt> </td>
<td class='confluenceTd'> <tt>List&lt;String&gt;</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> Allows to store headers as String which is human readable. By default this option is disabled, storing the headers in binary format. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>optimisticLocking</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> To turn on optimistic locking, which often would be needed in clustered environments where multiple Camel applications shared the same JDBC based aggregation repository. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>jdbcOptimisticLockingExceptionMapper</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.12:</b> Allows to plugin a custom <tt>org.apache.camel.processor.aggregate.jdbc.JdbcOptimisticLockingExceptionMapper</tt> to map vendor specific error codes to an optimistick locking error, for Camel to perform a retry. This requires <tt>optimisticLocking</tt> to be enabled. </td>
</tr>
</tbody></table>
</div>



<h4><a name="SQLComponent-Whatispreservedwhenpersisting"></a>What is preserved when persisting</h4>

<p><tt>JdbcAggregationRepository</tt> will only preserve any <tt>Serializable</tt> compatible data types. If a data type is not such a type its dropped and a <tt>WARN</tt> is logged. And it only persists the <tt>Message</tt> body and the <tt>Message</tt> headers. The <tt>Exchange</tt> properties are <b>not</b> persisted.</p>

<p>From Camel 2.11 onwards you can store the message body and select(ed) headers as String in separate columns.</p>

<h4><a name="SQLComponent-Recovery"></a>Recovery</h4>

<p>The <tt>JdbcAggregationRepository</tt> will by default recover any failed <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>. It does this by having a background tasks that scans for failed <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>s in the persistent store. You can use the <tt>checkInterval</tt> option to set how often this task runs. The recovery works as transactional which ensures that Camel will try to recover and redeliver the failed <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>. Any <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> which was found to be recovered will be restored from the persistent store and resubmitted and send out again.</p>

<p>The following headers is set when an <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> is being recovered/redelivered:</p>
<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Header </th>
<th class='confluenceTh'> Type </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>Exchange.REDELIVERED</tt> </td>
<td class='confluenceTd'> Boolean </td>
<td class='confluenceTd'> Is set to true to indicate the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> is being redelivered. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>Exchange.REDELIVERY_COUNTER</tt> </td>
<td class='confluenceTd'> Integer </td>
<td class='confluenceTd'> The redelivery attempt, starting from 1. </td>
</tr>
</tbody></table>
</div>


<p>Only when an <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> has been successfully processed it will be marked as complete which happens when the <tt>confirm</tt> method is invoked on the <tt>AggregationRepository</tt>. This means if the same <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> fails again it will be kept retried until it success.</p>

<p>You can use option <tt>maximumRedeliveries</tt> to limit the maximum number of redelivery attempts for a given recovered <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a>. You must also set the <tt>deadLetterUri</tt> option so Camel knows where to send the <a href="/confluence/display/CAMEL/Exchange" title="Exchange">Exchange</a> when the <tt>maximumRedeliveries</tt> was hit.</p>

<p>You can see some examples in the unit tests of camel-sql, for example <a href="https://svn.apache.org/repos/asf/camel/trunk/components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcAggregateRecoverDeadLetterChannelTest.java" class="external-link" rel="nofollow">this test</a>.</p>

<h4><a name="SQLComponent-Database"></a>Database</h4>

<p>To be operational, each aggregator uses two table: the aggregation and completed one. By convention the completed has the same name as the aggregation one suffixed with <tt>"_COMPLETED"</tt>. The name must be configured in the Spring bean with the <tt>RepositoryName</tt> property. In the following example aggregation will be used.</p>

<p>The table structure definition of both table are identical: in both case a String value is used as key (<b>id</b>) whereas a Blob contains the exchange serialized in byte array.<br/>
However one difference should be remembered: the <b>id</b> field does not have the same content depending on the table.<br/>
In the aggregation table <b>id</b> holds the correlation Id used by the component to aggregate the messages. In the completed table, <b>id</b> holds the id of the exchange stored in corresponding the blob field.</p>

<p>Here is the SQL query used to create the tables, just replace <tt>"aggregation"</tt> with your aggregator repository name.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
CREATE TABLE aggregation (
    id varchar(255) NOT NULL,
    exchange blob NOT NULL,
    constraint aggregation_pk PRIMARY KEY (id)
);
CREATE TABLE aggregation_completed (
    id varchar(255) NOT NULL,
    exchange blob NOT NULL,
    constraint aggregation_completed_pk PRIMARY KEY (id)
);
</pre>
</div></div>

<h4><a name="SQLComponent-Storingbodyandheadersastext"></a>Storing body and headers as text</h4>

<p><b>Available as of Camel 2.11</b></p>

<p>You can configure the <tt>JdbcAggregationRepository</tt> to store message body and select(ed) headers as String in separate columns. For example to store the body, and the following two headers <tt>companyName</tt> and <tt>accountName</tt> use the following SQL:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
CREATE TABLE aggregationRepo3 (
    id varchar(255) NOT NULL,
    exchange blob NOT NULL,
    body varchar(1000),
    companyName varchar(1000),
    accountName varchar(1000),
    constraint aggregationRepo3_pk PRIMARY KEY (id)
);
CREATE TABLE aggregationRepo3_completed (
    id varchar(255) NOT NULL,
    exchange blob NOT NULL,
    body varchar(1000),
    companyName varchar(1000),
    accountName varchar(1000),
    constraint aggregationRepo3_completed_pk PRIMARY KEY (id)
);
</pre>
</div></div>

<p>And then configure the repository to enable this behavior as shown below:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;bean id="repo3" class="org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository"&gt;
        &lt;property name="repositoryName" value="aggregationRepo3"/&gt;
        &lt;property name="transactionManager" ref="txManager3"/&gt;
        &lt;property name="dataSource" ref="dataSource3"/&gt;
        &lt;!-- configure to store the message body and following headers as text in the repo --&gt;
        &lt;property name="storeBodyAsText" value="true"/&gt;
        &lt;property name="headersToStoreAsText"&gt;
          &lt;list&gt;
      	    &lt;value&gt;companyName&lt;/value&gt;
    	    &lt;value&gt;accountName&lt;/value&gt;
          &lt;/list&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
</pre>
</div></div>

<h4><a name="SQLComponent-Codec%28Serialization%29"></a>Codec (Serialization)</h4>

<p>Since they can contain any type of payload, Exchanges are not serializable by design. It is converted into a byte array to be stored in a database BLOB field. All those conversions are handled by the <tt>JdbcCodec</tt> class. One detail of the code requires your attention: the <tt>ClassLoadingAwareObjectInputStream</tt>.</p>

<p>The <tt>ClassLoadingAwareObjectInputStream</tt> has been reused from the <a href="http://activemq.apache.org/" class="external-link" rel="nofollow">Apache ActiveMQ</a> project. It wraps an <tt>ObjectInputStream</tt> and use it with the <tt>ContextClassLoader</tt> rather than the <tt>currentThread</tt> one. The benefit is to be able to load classes exposed by other bundles. This allows the exchange body and headers to have custom types object references.</p>

<h4><a name="SQLComponent-Transaction"></a>Transaction</h4>

<p>A Spring <tt>PlatformTransactionManager</tt> is required to orchestrate transaction.</p>

<h4><a name="SQLComponent-Service%28Start%2FStop%29"></a>Service (Start/Stop)</h4>

<p>The <tt>start</tt> method verify the connection of the database and the presence of the required tables. If anything is wrong it will fail during starting.</p>

<h4><a name="SQLComponent-Aggregatorconfiguration"></a>Aggregator configuration</h4>

<p>Depending on the targeted environment, the aggregator might need some configuration. As you already know, each aggregator should have its own repository (with the corresponding pair of table created in the database) and a data source. If the default lobHandler is not adapted to your database system, it can be injected with the <tt>lobHandler</tt> property.</p>

<p>Here is the declaration for Oracle:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"&gt;
        &lt;property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/&gt;
    &lt;/bean&gt;

    &lt;bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/&gt;

    &lt;bean id="repo" class="org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository"&gt;
        &lt;property name="transactionManager" ref="transactionManager"/&gt;
        &lt;property name="repositoryName" value="aggregation"/&gt;
        &lt;property name="dataSource" ref="dataSource"/&gt;
        &lt;!-- Only with Oracle, else use default --&gt;
        &lt;property name="lobHandler" ref="lobHandler"/&gt;
    &lt;/bean&gt;
</pre>
</div></div>

<h3><a name="SQLComponent-Optimisticklocking"></a>Optimistick locking</h3>

<p>From <b>Camel 2.12</b> onwards you can turn on <tt>optimisticLocking</tt> and use this JDBC based aggregation repository in a clustered environment where multiple Camel applications shared the same database for the aggregation repository. If there is a race condition there JDBC driver will throw a vendor specific exception which the <tt>JdbcAggregationRepository</tt> can react upon. To know which caused exceptions from the JDBC driver is regarded as an optimistick locking error we need a mapper to do this. Therefore there is a <tt>org.apache.camel.processor.aggregate.jdbc.JdbcOptimisticLockingExceptionMapper</tt> allows you to implement your custom logic if needed. There is a default implementation <tt>org.apache.camel.processor.aggregate.jdbc.DefaultJdbcOptimisticLockingExceptionMapper</tt> which works as follows:</p>

<p>The following check is done:</p>
<ul class="alternate" type="square">
	<li>If the caused exception is an <tt>SQLException</tt> then the SQLState is checked if starts with 23.</li>
	<li>If the caused exception is a <tt>DataIntegrityViolationException</tt></li>
	<li>If the caused exception class name has "ConstraintViolation" in its name.</li>
	<li>optional checking for FQN class name matches if any class names has been configured</li>
</ul>


<p>You can in addition add FQN classnames, and if any of the caused exception (or any nested) equals any of the FQN class names, then its an optimistick locking error.</p>

<p>Here is an example, where we define 2 extra FQN class names from the JDBC vendor.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;bean id="repo" class="org.apache.camel.processor.aggregate.jdbc.JdbcAggregationRepository"&gt;
        &lt;property name="transactionManager" ref="transactionManager"/&gt;
        &lt;property name="repositoryName" value="aggregation"/&gt;
        &lt;property name="dataSource" ref="dataSource"/&gt;
        &lt;property name"jdbcOptimisticLockingExceptionMapper" ref="myExceptionMapper"/&gt;
    &lt;/bean&gt;

    &lt;!-- use the default mapper with extra FQN class names from our JDBC driver --&gt;
    &lt;bean id="myExceptionMapper" class="org.apache.camel.processor.aggregate.jdbc.DefaultJdbcOptimisticLockingExceptionMapper"&gt;
      &lt;property name="classNames"&gt;
        &lt;util:set&gt;
          &lt;value&gt;com.foo.sql.MyViolationExceptoion&lt;/value&gt;
          &lt;value&gt;com.foo.sql.MyOtherViolationExceptoion&lt;/value&gt;
        &lt;/util:set&gt;
      &lt;/property&gt;
    &lt;/bean&gt;
</pre>
</div></div>


<h3><a name="SQLComponent-SeeAlso"></a>See Also</h3>
<ul>
	<li><a href="/confluence/display/CAMEL/Configuring+Camel" title="Configuring Camel">Configuring Camel</a></li>
	<li><a href="/confluence/display/CAMEL/Component" title="Component">Component</a></li>
	<li><a href="/confluence/display/CAMEL/Endpoint" title="Endpoint">Endpoint</a></li>
	<li><a href="/confluence/display/CAMEL/Getting+Started" title="Getting Started">Getting Started</a></li>
</ul>

<ul class="alternate" type="square">
	<li><a href="/confluence/display/CAMEL/JDBC" title="JDBC">JDBC</a></li>
</ul>

    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;" class="grey">
                        <a href="https://cwiki.apache.org/confluence/users/removespacenotification.action?spaceKey=CAMEL">Stop watching space</a>
            <span style="padding: 0px 5px;">|</span>
                <a href="https://cwiki.apache.org/confluence/users/editmyemailsettings.action">Change email notification preferences</a>
</div>
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/SQL+Component">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=82932&revisedVersion=56&originalVersion=55">View Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/SQL+Component?showComments=true&amp;showCommentArea=true#addcomment">Add Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message