camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Claus Ibsen (Confluence)" <conflue...@apache.org>
Subject [CONF] Apache Camel > JDBC
Date Wed, 18 Sep 2013 13:01: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/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 (3)</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" >h3. Options <br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">{div:class=confluenceTableSmall}
<br></td></tr>
            <tr><td class="diff-unchanged" >|| Name || Default Value || Description
|| <br>| {{readSize}} | {{0}} | The default maximum number of rows that can be read
by a polling query. The default value is 0. | <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >| {{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-added-lines" style="background-color: #dfd;">|
{{outputType}} | {{SelectList}} | *Camel 2.12.1:* Make the output of the producer to SelectList
as List of Map, or SelectOne 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 SELECT COUNT(
* ) FROM PROJECT 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 query resulted in more than
one rows, it throws an non-unique result exception. <br>|  <br>{div} <br></td></tr>
            <tr><td class="diff-unchanged" > <br>h3. Result <br></td></tr>
            <tr><td class="diff-changed-lines" ><span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">The</span>
<span class="diff-added-words"style="background-color: #dfd;">By default the</span>
result is returned in the OUT body as an {{ArrayList&lt;HashMap&lt;String, Object&gt;&gt;}}.
The {{List}} object contains the list of rows and the {{Map}} objects contain each row with
the {{String}} key as the column name. <span class="diff-added-words"style="background-color:
#dfd;">You can use the option {{outputType}} to control the result.</span> <br></td></tr>
            <tr><td class="diff-unchanged" > <br>*Note:* This component
fetches {{ResultSetMetaData}} to be able to return the column name as the key in the {{Map}}.
<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="theme: Default; brush: java; 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-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="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
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="confluenceTableSmall"><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>
<tr>
<td class='confluenceTd'> <tt>outputType</tt> </td>
<td class='confluenceTd'> <tt>SelectList</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12.1:</b> Make the output of the producer
to SelectList as List of Map, or SelectOne 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
SELECT COUNT( * ) FROM PROJECT 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 query resulted in more than one rows, it throws an non-unique result exception.</td>
</tr>
<tr>
</tr>
</tbody></table>
</div>
</div>

<h3><a name="JDBC-Result"></a>Result</h3>
<p>By default 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. You can use the option <tt>outputType</tt> to control
the result.</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 these parameters from the 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))
     .setBody("select * from projects where license = :?lic and id &gt; :?min order by
id")
     .to("jdbc:myDataSource?useHeadersAsParameters=true")
</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">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
JndiRegistry reg = super.createRegistry();
reg.bind("testdb", db);
return reg;
]]></script>
</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">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// lets add simple route
public void configure() throws Exception {
    from("direct:hello").to("jdbc:testdb?readSize=100");
}
]]></script>
</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">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
&lt;camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"&gt;
  &lt;route&gt;
	 &lt;!-- trigger every second --&gt;
     &lt;from uri="timer://kickoff?period=1s"/&gt;
     &lt;setBody&gt;
       &lt;constant&gt;select * from customer&lt;/constant&gt;
     &lt;/setBody&gt;
     &lt;to uri="jdbc:testdb"/&gt;
     &lt;to uri="mock:result"/&gt;
  &lt;/route&gt;
&lt;/camelContext&gt;

&lt;!-- Just add a demo to show how to bind a date source for camel in Spring--&gt;
&lt;jdbc:embedded-database id="testdb" type="DERBY"&gt;
	&lt;jdbc:script location="classpath:sql/init.sql"/&gt;
&lt;/jdbc:embedded-database&gt;
]]></script>
</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">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
// first we create our exchange using the endpoint
Endpoint endpoint = context.getEndpoint("direct:hello");
Exchange exchange = endpoint.createExchange();
// then we set the SQL on the in body
exchange.getIn().setBody("select * from customer order by ID");

// now we send the exchange to the endpoint, and receives the response from Camel
Exchange out = template.send(endpoint, exchange);

// assertions of the response
assertNotNull(out);
assertNotNull(out.getOut());
List&lt;Map&lt;String, Object&gt;&gt; data = out.getOut().getBody(List.class);
assertNotNull(data);
assertEquals(3, data.size());
Map&lt;String, Object&gt; row = data.get(0);
assertEquals("cust1", row.get("ID"));
assertEquals("jstrachan", row.get("NAME"));
row = data.get(1);
assertEquals("cust2", row.get("ID"));
assertEquals("nsandhu", row.get("NAME"));
]]></script>
</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">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
from("direct:hello")
        // here we split the data from the testdb into new messages one by one
        // so the mock endpoint will receive a message per row in the table
    .to("jdbc:testdb").split(body()).to("mock:result");

]]></script>
</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="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
from("timer://foo?period=60000").setBody(constant("select * from customer")).to("jdbc:testdb").to("activemq:queue:customers");
</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;" 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/JDBC">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=64933&revisedVersion=26&originalVersion=25">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