camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Camel > JDBC
Date Sun, 02 Jun 2013 15:22:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/2042/9/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/JDBC">JDBC</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~davsclaus">Claus
Ibsen</a>
    </h4>
        <br/>
                         <h4>Changes (4)</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" >| {{useJDBC4ColumnNameAndLabelSemantics}}
| {{true}} | *Camel 2.2:* Sets whether to use JDBC 4/3 column label/name semantics. You can
use this option to turn it {{false}} in case you have issues with your JDBC driver to select
data. This only applies when using {{SQL SELECT}} using aliases (e.g. {{SQL SELECT id as identifier,
name as given_name from persons}}). | <br>| {{resetAutoCommit}} | {{true}} | *Camel
2.9:* Camel will set the autoCommit on the JDBC connection to be false, commit the change
after executed the statement and reset the autoCommit flag of the connection at the end, if
the resetAutoCommit is true. If the JDBC connection doesn&#39;t support to reset the autoCommit
flag, you can set the resetAutoCommit flag to be false, and Camel will not try to reset the
autoCommit flag.| <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">|
{{allowNamedParameters}} | {{true}} | *Camel 2.12:* Whether to allow using named parameters
in the queries. | <br>| {{prepareStatementStrategy}} | | *Camel 2.12:* Allows to plugin
to use a custom {{org.apache.camel.component.jdbc.JdbcPrepareStatementStrategy}} to control
preparation of the query and prepared statement. | <br>| {{useHeadersAsParameters}}
| {{false}} | *Camel 2.12:* Set this option to {{true}} to use the {{prepareStatementStrategy}}
with named parameters. This allows to define queries with named placeholders, and use headers
with the dynamic values for the query placeholders. | <br></td></tr>
            <tr><td class="diff-unchanged" > <br>h3. Result <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >| {{CamelGeneratedKeysRowCount}} |
*Camel 2.10:* The number of rows in the header that contains generated keys. | <br>|
{{CamelJdbcColumnNames}} | *Camel 2.11.1:* The column names from the ResultSet as a {{java.util.Set}}
type. | <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">|
{{CamelJdbcParametes}} | *Camel 2.12:* A {{java.util.Map}} which has the headers to be used
if {{useHeadersAsParameters}} has been enabled. | <br></td></tr>
            <tr><td class="diff-unchanged" > <br>h3. Generated keys <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >You can see more details in this [unit
test|https://svn.apache.org/repos/asf/camel/trunk/components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcGeneratedKeysTest.java].
<br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">{info}
<br>Using generated keys does not work with together with named parameters. <br>{info}
<br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">
<br>h3. Using named parameters <br>*Available as of Camel 2.12* <br> <br>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: <br> <br>{code}
<br>  from(&quot;direct:projects&quot;) <br>     .setHeader(&quot;lic&quot;,
constant(&quot;ASF&quot;)) <br>     .setHeader(&quot;min&quot;, constant(123))
<br>     .setBody(&quot;select * from projects where license = :#lic and id &gt;
:#min order by id&quot;) <br>     .to(&quot;jdbc:myDataSource?useHeadersAsParameters=true&quot;)
<br>{code} <br> <br>You can also store the header values in a {{java.util.Map}}
and store the map on the headers with the key {{CamelJdbcParameters}}. <br> <br>
<br></td></tr>
            <tr><td class="diff-unchanged" >h3. Samples <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h2><a name="JDBC-JDBCComponent"></a>JDBC Component</h2>

<p>The <b>jdbc</b> component enables you to access databases through JDBC,
where SQL queries and operations are sent in the message body. This component uses the standard
JDBC API, unlike the <a href="/confluence/display/CAMEL/SQL+Component" title="SQL Component">SQL
Component</a> component, which uses spring-jdbc.</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="code-java">
&lt;dependency&gt;
    &lt;groupId&gt;org.apache.camel&lt;/groupId&gt;
    &lt;artifactId&gt;camel-jdbc&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>

<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>This component can
only be used to define producer endpoints, which means that you cannot use the JDBC component
in a <tt>from()</tt> statement.</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
not be used as a <a href="http://camel.apache.org/transactional-client.html" class="external-link"
rel="nofollow">Transactional Client</a>. If you need transaction support in your
route, you should use the <a href="http://camel.apache.org/sql-component.html" class="external-link"
rel="nofollow">SQL component</a> instead.</td></tr></table></div>

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

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
jdbc:dataSourceName[?options]
</pre>
</div></div>

<p>This component only supports producer endpoints.</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="JDBC-Options"></a>Options</h3>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Name </th>
<th class='confluenceTh'> Default Value </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>readSize</tt> </td>
<td class='confluenceTd'> <tt>0</tt> </td>
<td class='confluenceTd'> The default maximum number of rows that can be read by a polling
query. The default value is 0. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>statement.&lt;xxx&gt;</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.1:</b> Sets additional options on the
<tt>java.sql.Statement</tt> that is used behind the scenes to execute the queries.
For instance, <tt>statement.maxRows=10</tt>. For detailed documentation, see the
<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Statement.html" class="external-link"
rel="nofollow"><tt>java.sql.Statement</tt> javadoc</a> documentation.
</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>useJDBC4ColumnNameAndLabelSemantics</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.2:</b> Sets whether to use JDBC 4/3
column label/name semantics. You can use this option to turn it <tt>false</tt>
in case you have issues with your JDBC driver to select data. This only applies when using
<tt>SQL SELECT</tt> using aliases (e.g. <tt>SQL SELECT id as identifier,
name as given_name from persons</tt>). </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>resetAutoCommit</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.9:</b> Camel will set the autoCommit
on the JDBC connection to be false, commit the change after executed the statement and reset
the autoCommit flag of the connection at the end, if the resetAutoCommit is true. If the JDBC
connection doesn't support to reset the autoCommit flag, you can set the resetAutoCommit flag
to be false, and Camel will not try to reset the autoCommit flag.</td>
</tr>
<tr>
<td class='confluenceTd'> <tt>allowNamedParameters</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> Whether to allow using named
parameters in the queries. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>prepareStatementStrategy</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.12:</b> Allows to plugin to use a custom
<tt>org.apache.camel.component.jdbc.JdbcPrepareStatementStrategy</tt> to control
preparation of the query and prepared statement. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>useHeadersAsParameters</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> Set this option to <tt>true</tt>
to use the <tt>prepareStatementStrategy</tt> with named parameters. This allows
to define queries with named placeholders, and use headers with the dynamic values for the
query placeholders. </td>
</tr>
</tbody></table>
</div>


<h3><a name="JDBC-Result"></a>Result</h3>
<p>The result is returned in the OUT body as an <tt>ArrayList&lt;HashMap&lt;String,
Object&gt;&gt;</tt>. The <tt>List</tt> object contains the list
of rows and the <tt>Map</tt> objects contain each row with the <tt>String</tt>
key as the column name.</p>

<p><b>Note:</b> This component fetches <tt>ResultSetMetaData</tt>
to be able to return the column name as the key in the <tt>Map</tt>.</p>

<h4><a name="JDBC-MessageHeaders"></a>Message Headers</h4>
<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>CamelJdbcRowCount</tt> </td>
<td class='confluenceTd'> If the query is a <tt>SELECT</tt>, query the row
count is returned in this OUT header. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelJdbcUpdateCount</tt> </td>
<td class='confluenceTd'> If the query is an <tt>UPDATE</tt>, query the
update count is returned in this OUT header. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelGeneratedKeysRows</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10:</b> Rows that contains the generated
kets. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelGeneratedKeysRowCount</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10:</b> The number of rows in the header
that contains generated keys. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelJdbcColumnNames</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> The column names from the
ResultSet as a <tt>java.util.Set</tt> type. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>CamelJdbcParametes</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> A <tt>java.util.Map</tt>
which has the headers to be used if <tt>useHeadersAsParameters</tt> has been enabled.
</td>
</tr>
</tbody></table>
</div>


<h3><a name="JDBC-Generatedkeys"></a>Generated keys</h3>
<p><b>Available as of Camel 2.10</b></p>

<p>If you insert data using SQL INSERT, then the RDBMS may support auto generated keys.
You can instruct the <a href="/confluence/display/CAMEL/JDBC" title="JDBC">JDBC</a>
producer to return the generated keys in headers.<br/>
To do that set the header <tt>CamelRetrieveGeneratedKeys=true</tt>. Then the generated
keys will be provided as headers with the keys listed in the table above.</p>

<p>You can see more details in this <a href="https://svn.apache.org/repos/asf/camel/trunk/components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcGeneratedKeysTest.java"
class="external-link" rel="nofollow">unit test</a>.</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>Using generated keys
does not work with together with named parameters.</td></tr></table></div>


<h3><a name="JDBC-Usingnamedparameters"></a>Using named parameters</h3>
<p><b>Available as of Camel 2.12</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="code-java">
  from(<span class="code-quote">"direct:projects"</span>)
     .setHeader(<span class="code-quote">"lic"</span>, constant(<span class="code-quote">"ASF"</span>))
     .setHeader(<span class="code-quote">"min"</span>, constant(123))
     .setBody(<span class="code-quote">"select * from projects where license = :#lic
and id &gt; :#min order by id"</span>)
     .to(<span class="code-quote">"jdbc:myDataSource?useHeadersAsParameters=<span
class="code-keyword">true</span>"</span>)
</pre>
</div></div>

<p>You can also store the header values in a <tt>java.util.Map</tt> and
store the map on the headers with the key <tt>CamelJdbcParameters</tt>.</p>


<h3><a name="JDBC-Samples"></a>Samples</h3>

<p>In the following example, we fetch the rows from the customer table.</p>

<p>First we register our datasource in the Camel registry as <tt>testdb</tt>:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">JndiRegistry reg = <span class="code-keyword">super</span>.createRegistry();
reg.bind(<span class="code-quote">"testdb"</span>, db);
<span class="code-keyword">return</span> reg;
</pre>
</div></div>

<p>Then we configure a route that routes to the JDBC component, so the SQL will be executed.
Note how we refer to the <tt>testdb</tt> datasource that was bound in the previous
step:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java"><span class="code-comment">// lets add simple route
</span><span class="code-keyword">public</span> void configure() <span
class="code-keyword">throws</span> Exception {
    from(<span class="code-quote">"direct:hello"</span>).to(<span class="code-quote">"jdbc:testdb?readSize=100"</span>);
}
</pre>
</div></div>

<p>Or you can create a <tt>DataSource</tt> in Spring like this:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">&lt;camelContext id=<span class="code-quote">"camel"</span>
xmlns=<span class="code-quote">"http:<span class="code-comment">//camel.apache.org/schema/spring"</span>&gt;
</span>  &lt;route&gt;
	 &lt;!-- trigger every second --&gt;
     &lt;from uri=<span class="code-quote">"timer:<span class="code-comment">//kickoff?period=1s"</span>/&gt;
</span>     &lt;setBody&gt;
       &lt;constant&gt;select * from customer&lt;/constant&gt;
     &lt;/setBody&gt;
     &lt;to uri=<span class="code-quote">"jdbc:testdb"</span>/&gt;
     &lt;to uri=<span class="code-quote">"mock:result"</span>/&gt;
  &lt;/route&gt;
&lt;/camelContext&gt;

&lt;!-- Just add a demo to show how to bind a date source <span class="code-keyword">for</span>
camel in Spring--&gt;
&lt;jdbc:embedded-database id=<span class="code-quote">"testdb"</span> type=<span
class="code-quote">"DERBY"</span>&gt;
	&lt;jdbc:script location=<span class="code-quote">"classpath:sql/init.sql"</span>/&gt;
&lt;/jdbc:embedded-database&gt;
</pre>
</div></div>

<p>We create an endpoint, add the SQL query to the body of the IN message, and then
send the exchange. The result of the query is returned in the OUT body:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java"><span class="code-comment">// first we create our exchange
using the endpoint
</span>Endpoint endpoint = context.getEndpoint(<span class="code-quote">"direct:hello"</span>);
Exchange exchange = endpoint.createExchange();
<span class="code-comment">// then we set the SQL on the in body
</span>exchange.getIn().setBody(<span class="code-quote">"select * from customer
order by ID"</span>);

<span class="code-comment">// now we send the exchange to the endpoint, and receives
the response from Camel
</span>Exchange out = template.send(endpoint, exchange);

<span class="code-comment">// assertions of the response
</span>assertNotNull(out);
assertNotNull(out.getOut());
List&lt;Map&lt;<span class="code-object">String</span>, <span class="code-object">Object</span>&gt;&gt;
data = out.getOut().getBody(List.class);
assertNotNull(data);
assertEquals(3, data.size());
Map&lt;<span class="code-object">String</span>, <span class="code-object">Object</span>&gt;
row = data.get(0);
assertEquals(<span class="code-quote">"cust1"</span>, row.get(<span class="code-quote">"ID"</span>));
assertEquals(<span class="code-quote">"jstrachan"</span>, row.get(<span class="code-quote">"NAME"</span>));
row = data.get(1);
assertEquals(<span class="code-quote">"cust2"</span>, row.get(<span class="code-quote">"ID"</span>));
assertEquals(<span class="code-quote">"nsandhu"</span>, row.get(<span class="code-quote">"NAME"</span>));
</pre>
</div></div>

<p>If you want to work on the rows one by one instead of the entire ResultSet at once
you need to use the <a href="/confluence/display/CAMEL/Splitter" title="Splitter">Splitter</a>
EIP such as:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">from(<span class="code-quote">"direct:hello"</span>)
        <span class="code-comment">// here we split the data from the testdb into <span
class="code-keyword">new</span> messages one by one
</span>        <span class="code-comment">// so the mock endpoint will receive
a message per row in the table
</span>    .to(<span class="code-quote">"jdbc:testdb"</span>).split(body()).to(<span
class="code-quote">"mock:result"</span>);

</pre>
</div></div>

<h3><a name="JDBC-SamplePollingthedatabaseeveryminute"></a>Sample - Polling
the database every minute</h3>
<p>If we want to poll a database using the JDBC component, we need to combine it with
a polling scheduler such as the <a href="/confluence/display/CAMEL/Timer" title="Timer">Timer</a>
or <a href="/confluence/display/CAMEL/Quartz" title="Quartz">Quartz</a> etc. In
the following example, we retrieve data from the database every 60 seconds:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
from(<span class="code-quote">"timer:<span class="code-comment">//foo?period=60000"</span>).setBody(constant(<span
class="code-quote">"select * from customer"</span>)).to(<span class="code-quote">"jdbc:testdb"</span>).to(<span
class="code-quote">"activemq:queue:customers"</span>);</span>
</pre>
</div></div>


<h3><a name="JDBC-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/SQL" title="SQL">SQL</a></li>
</ul>

    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;">
            <a href="https://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
        </div>
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/JDBC">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=64933&revisedVersion=24&originalVersion=23">View
Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/JDBC?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message