JDBC

JDBC Component

The jdbc 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 SQL Component component, which uses spring-jdbc.

URI format

jdbc:dataSourceName[?options]

This component supports producer endpoints only.

You can append query options to the URI in the following format, ?option=value&option=value&...

Dependencies

Maven users need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-jdbc</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
[Warning]Warning

This component can only be used to define producer endpoints, which means that you cannot use the JDBC component in a from() statement.

[Important]Important

This component cannot be used as a transactional client. If you need transaction support in your route, use the SQL Component component instead.

Options

Name Description
readSize

The default maximum number of rows that can be read by a polling query.

The defaut is 0.

statement.<xxx>

Apache Camel 2.1: Sets additional options on the java.sql.Statement, which is used behind the scenes to execute the queries. For example, statement.maxRows=10.

For details, see the java.sql.Statement javadoc documentation.

The default is null.

useJDBC4ColumnNameAndLabel Semantics

Specifies whether to use JDBC 4/3 column label/name semantics. Set this option to false if you have issues with your JDBC driver selecting data. This only applies when using SQL SELECT using aliases (e.g. SQL SELECT id as identifier, name as given_name from persons).

The default is true.

resetAutoCommit

Camel 2.9: Camel sets the autoCommit on the JDBC connection to false, commits the change after executing the statement, and resets the autoCommit flag of the connection at the end if resetAutoCommit is true.

If the JDBC connection doesn't support resetting the autoCommit flag, you can set the resetAutoCommit flag to false, to prevent Camel from trying to reset the autoCommit flag.

The default is true.

allowNamedParameters

Camel 2.12: Whether to allow using named parameters in the queries.

The default is true.

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.

The default is prepareStatementStrategy.

useHeadersAsParameters

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.

The default is false.

outputType

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:

  • If the query has only a single column, that JDBC Column object is returned (like SELECT COUNT( * ) FROM PROJECT returns a Long object.

  • If the query has more than one column, it returns a Map of that result.

  • If the outputClass is set, it converts the query result to an Java bean object by calling all the setters that match the column names. It assumes your class has a default constructor with which to create instance.

  • If the query resulted in more than one row, it throws an non unique result exception.

The default is SelectList.

outputClass

Camel 2.12.1: Specify the full package and class name to use as conversion when outputType=SelectOne.

The default is null.

beanRowMapper

Camel 2.12.1: To use a custom org.apache.camel.component.jdbc.BeanRowMapper when using outputClass. The default implementation will lower case the row names and skip underscores, and dashes. For example "CUST_ID" is mapped as "custId".

Result

By default, the result is returned in the OUT body as an ArrayList<HashMap<String, Object>>. The List object contains the list of rows and the Map objects contain each row with the String key as the column name.

[Note]Note

This component fetches ResultSetMetaData to be able to return the column name as the key in the Map.

Message Headers

Header Description
CamelJdbcRowCount If the query is a SELECT, the row count is returned in this OUT header.
CamelJdbcUpdateCount If the query is an UPDATE, the update count is returned in this OUT header.
CamelGeneratedKeysRows Camel 2.10: Rows that contains the generated kets.
CamelGeneratedKeysRowCount Camel 2.10: The number of rows in the header that contains generated keys.
CamelJdbcColumnNames Camel 2.11.1: The column names from the ResultSet as a java.util.Set type.
CamelJdbcParametes Camel 2.12: A java.util.Map which has the headers to be used if useHeadersAsParameters has been enabled.

Generated Keys

Available as of 2.10.

The RDBMS may support autogenerated keys if you insert data using SQL INSERT. If so, you can instruct the JDBC producer to return the generated keys in headers. To do so, set the header CamelRetrieveGenerateKeys=true, and then the generated keys will be returned as headers with the keys listed in Message Headers.

You can see more details in this unit test.

[Important]Important

Using generated keys does not work with together with named parameters.

Using named parameters

Available as of Camel 2.12

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. Camel will then lookup these parameters from the message headers. Notice in the example above we set two headers with constant value for the named parameters:

  from("direct:projects")
     .setHeader("lic", constant("ASF"))
     .setHeader("min", constant(123))
     .setBody("select * from projects where license = :?lic and id > :?min order by id")
     .to("jdbc:myDataSource?useHeadersAsParameters=true")

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

Samples

In the following example, we fetch the rows from the customer table.

First we register our datasource in the Apache Camel registry as testdb:

JndiRegistry reg = super.createRegistry();
reg.bind("testdb", ds);
return reg;

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

// lets add simple route
public void configure() throws Exception {
    from("direct:hello").to("jdbc:testdb?readSize=100");
}

Or you can create a DataSource in Spring like this:

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
  <route>
     <from uri="timer://kickoff?period=10000"/>
     <setBody>
       <constant>select * from customer</constant>
     </setBody>
     <to uri="jdbc:testdb"/>
     <to uri="mock:result"/>
  </route>
</camelContext>
<!-- Just add a demo to show how to bind a date source for camel in Spring-->
<bean id="testdb" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
	<property name="url" value="jdbc:hsqldb:mem:camel_jdbc" />
	<property name="username" value="sa" />
  <property name="password" value="" />
</bean>	

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:

// 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());
ArrayList<HashMap<String, Object>> data = out.getOut().getBody(ArrayList.class);
assertNotNull("out body could not be converted to an ArrayList - was: "
    + out.getOut().getBody(), data);
assertEquals(2, data.size());
HashMap<String, Object> 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"));

If you want to work on the rows one by one instead of the entire ResultSet at once you need to use the Splitter EIP such as:

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");

Sample - Polling the database every minute

If we want to poll a database using the JDBC component, we need to combine it with a polling scheduler such as the Timer or Quartz etc. In the following example, we retrieve data from the database every 60 seconds:

from("timer://foo?period=60000").setBody(constant("select * from customer")).to("jdbc:testdb").to("activemq:queue:customers");

See also: