Camel Components

JDBC

Since Camel 1.2

Only producer is supported

The JDBC component enables you to access databases through JDBC, where SQL queries (SELECT) and operations (INSERT, UPDATE, etc.) are sent in the message body. This component uses the standard JDBC API, unlike the SQL Component, which uses spring-jdbc.

When you use Spring and need to support Spring Transactions, use the Spring JDBC Component instead of this one.

Maven users will 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>

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

URI format

jdbc:dataSourceName[?options]

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The JDBC component supports the following options which are listed below.

Name Description Default Type

dataSource (producer)

The javax.sql.DataSource to use for all the endpoints of this component, instead of looking up the dataSourceName of the endpoint in the registry.

DataSource

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

connectionStrategy (advanced)

A custom ConnectionStrategy for all the endpoints of this component, that gets the java.sql.Connection from the DataSource (the default calls DataSource.getConnection()) and tells whether the connection takes part in a transaction: with resetAutoCommit=false such a connection is closed only when the exchange is done. Do not set it with the spring-jdbc component, whose strategy takes part in Spring transactions.

ConnectionStrategy

Endpoint Options

The JDBC endpoint is configured using URI syntax:

jdbc:dataSourceName

With the following path and query parameters:

Path Parameters

Name Description Default Type

dataSourceName (producer)

Required The name of the javax.sql.DataSource to look up in the registry. With the name dataSource or default, when the registry has no bean of that name, the only DataSource of the registry is used (creating the endpoint fails when there is none or more than one). Not used when the dataSource option of the component is set.

String

Query Parameters

Name Description Default Type

allowNamedParameters (producer)

Whether to replace the named parameters (:?name) of the query with ? placeholders before the PreparedStatement is created. When false, the query reaches the driver unchanged. Only used with useHeadersAsParameters=true.

true

boolean

outputClass (producer)

The fully qualified name of a class to create for each row instead of a Map, with any outputType. The class is created with its no-argument constructor, and each column sets the property whose name beanRowMapper maps the column name to; a column without such a property fails the exchange.

String

outputType (producer)

The body the producer returns for the ResultSet of a select. SelectList: a List with a Map of the column names and values (or an outputClass bean) per row. SelectOne: the one row (a Map, an outputClass bean, or the value of its only column), null when there is no row, and an SQLDataException when there is more than one. StreamList: an Iterator that reads the rows from the open ResultSet, which is closed, with its Statement and Connection, when the exchange is done.

Enum values:

  • SelectOne

  • SelectList

  • StreamList

SelectList

JdbcOutputType

parameters (producer)

Properties to set on each java.sql.Statement (or PreparedStatement) before it runs, by the name of its setter, for example statement.maxRows (Statement.setMaxRows, the most rows the database returns, 0 = no limit), statement.fetchSize (Statement.setFetchSize, the number of rows the driver fetches at a time, a hint, 0 = the driver decides) or statement.queryTimeout (Statement.setQueryTimeout, in seconds, 0 = no limit). A name that is not a property of the statement is ignored. This is a multi-value option with prefix: statement.

Map

readSize (producer)

The maximum number of rows to read from the java.sql.ResultSet into the List body with outputType=SelectList; the rows after that are not read. 0 means no limit. It is not used with SelectOne or StreamList, nor for the generated keys, and it is not passed to the java.sql.Statement: use statement.maxRows to have the database return fewer rows.

int

resetAutoCommit (producer)

Whether the producer runs each statement in a transaction of its own on the java.sql.Connection. When true, it turns off the auto-commit mode of the connection (Connection.setAutoCommit(false)) if it is on, commits after the statement, or rolls back when it fails, and then restores the auto-commit mode; it also commits when the connection was not in auto-commit mode. With outputType=StreamList the commit, or the rollback when the exchange fails, happens when the exchange is done. When false, the producer neither changes the auto-commit mode nor commits or rolls back: the auto-commit mode of the connection, or a transaction manager (XA or Spring), ends the transaction. Set it to false also for a driver that does not support changing the auto-commit mode.

true

boolean

transacted (producer)

Deprecated Has no effect. To take part in a Spring transaction, use the spring-jdbc component. Deprecation note: Not used: the producer does not read this option.

false

boolean

useGetBytesForBlob (producer)

Whether to read the BLOB columns with ResultSet.getBytes, as a byte[], instead of with ResultSet.getBlob, as a java.sql.Blob, which can be read only while the connection is open: the producer closes it before the route continues (with outputType=StreamList when the exchange is done). Some databases, such as Oracle, need it. CLOB columns are always read as a java.sql.Clob.

false

boolean

useHeadersAsParameters (producer)

Whether to run the query as a java.sql.PreparedStatement and set the values of its parameters from the message: the named parameters (:?name) from the Map in the CamelJdbcParameters header, or else from the message headers of the same names, and plain ? placeholders, in order, only from the CamelJdbcParameters header (a List). When false, the query runs as a plain java.sql.Statement, without parameters.

false

boolean

useJDBC4ColumnNameAndLabelSemantics (producer)

How to get the column names, which are the keys of the row Maps and the values of the CamelJdbcColumnNames header. When true, with ResultSetMetaData.getColumnLabel (JDBC 4.0: the alias of the AS clause, or else the column name). When false, also with getColumnLabel, but falling back to ResultSetMetaData.getColumnName when the driver throws an SQLException from getColumnLabel.

true

boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

beanRowMapper (advanced)

A custom BeanRowMapper that maps a column name to the name of the outputClass property to set. The default lower-cases the name, drops underscores and dashes, and upper-cases the letter after them: CUST_ID becomes custId.

BeanRowMapper

connectionStrategy (advanced)

A custom ConnectionStrategy that gets the java.sql.Connection from the DataSource (the default calls DataSource.getConnection()) and tells whether the connection takes part in a transaction: with resetAutoCommit=false such a connection is closed only when the exchange is done. Do not set it with the spring-jdbc component, whose strategy takes part in Spring transactions.

ConnectionStrategy

prepareStatementStrategy (advanced)

A custom JdbcPrepareStatementStrategy, used with useHeadersAsParameters=true, that turns the query into the SQL to prepare (the default replaces the named parameters :?name with ? placeholders) and sets the values of its parameters on the PreparedStatement (the default with PreparedStatement.setObject).

JdbcPrepareStatementStrategy

Message Headers

The JDBC component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelJdbcUpdateCount (producer)

Constant: JDBC_UPDATE_COUNT

The update count (Statement.getUpdateCount()) of a statement that returns no ResultSet, such as an INSERT, UPDATE, DELETE or DDL statement; the body is then unchanged.

int

CamelJdbcRowCount (producer)

Constant: JDBC_ROW_COUNT

The number of rows in the List body of a select with outputType=SelectList (at most readSize when it is set).

int

CamelJdbcColumnNames (producer)

Constant: JDBC_COLUMN_NAMES

The column names of the ResultSet of a select, in column order, as a java.util.Set.

Set

CamelJdbcParameters (producer)

Constant: JDBC_PARAMETERS

The values of the query parameters when useHeadersAsParameters has been enabled: a java.util.Map with the values of the named parameters, or a java.util.List with the values of the positional placeholders, in order (a single value for one placeholder).

Object

CamelRetrieveGeneratedKeys (producer)

Constant: JDBC_RETRIEVE_GENERATED_KEYS

Set to true to retrieve the keys that the database generates for the statement, such as an INSERT (Statement.getGeneratedKeys()), into the CamelGeneratedKeysRows and CamelGeneratedKeysRowCount headers.

false

Boolean

CamelGeneratedColumns (producer)

Constant: JDBC_GENERATED_COLUMNS

The columns whose generated values to return when CamelRetrieveGeneratedKeys is true: a String[] of column names or an int[] of column indexes. When not set, the driver chooses the columns (Statement.RETURN_GENERATED_KEYS); any other type fails the exchange.

String[] or int[]

CamelGeneratedKeysRowCount (producer)

Constant: JDBC_GENERATED_KEYS_ROW_COUNT

The number of rows of generated keys in the CamelGeneratedKeysRows header.

int

CamelGeneratedKeysRows (producer)

Constant: JDBC_GENERATED_KEYS_DATA

The generated keys of the statement: a List with a Map of the key column names and values per row.

List

Message Body

The message body at each side of the JDBC component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Producer input

text, bytes, stream or file

The SQL statement as text, or bytes, a stream or a file of it; a Map or a List is not a statement: set the SQL as the body. With useHeadersAsParameters, the values of its named parameters (:?name) come from the CamelJdbcParameters header, or else from the headers, and the values of plain ? placeholders, in order, only from the CamelJdbcParameters header.

Producer output

list or unchanged

The rows of a select: a List of Maps of the column names and their values (beans of outputClass when set). SelectOne gives the Map of the one row, the value of its column as the driver reads it when it has one, or null for no row; StreamList an Iterator of the rows, read once. A statement that is not a select leaves the body unchanged, with the count in the CamelJdbcUpdateCount header.

  • With outputType=SelectOne: map, text, value, bytes, pojo, null or unchanged, or an object of the class outputClass names when it is set

  • With outputType=StreamList: iterator or unchanged

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Result

By default, the result of a select is returned in the OUT body as an ArrayList<LinkedHashMap<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. You can use the option outputType to control the result: SelectOne gives the Map of the one row, the value of its column when it has one column, or null when there is no row, and StreamList gives an Iterator of the rows, which can be read once. A statement that is not a select leaves the body as it is, with the count in the CamelJdbcUpdateCount header.

When reading a row of a StreamList fails (for example, the connection is lost), the iterator keeps failing instead of ending, so a split that is redelivered over it fails too, rather than succeeding with the rows read before the failure. The same applies when a row cannot be mapped to the outputClass (for example, a value that does not convert to the type of its property): the iterator keeps failing instead of going on with the next row, so a redelivered split does not skip that row.

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

With outputType=SelectList the header CamelJdbcRowCount holds the number of rows of the result.

A BLOB or CLOB value of a row is a java.sql.Blob or java.sql.Clob, which can be read only while the connection is open, and the producer closes the connection before the route continues (except with outputType=StreamList, which closes it when the exchange is done). So read such a value inside the producer: set useGetBytesForBlob=true to get a BLOB as a byte[], or convert a CLOB to text in the SQL query with a function of the database.

The SQL of the message body is mandatory: a message without a body fails with an InvalidPayloadException.

The transacted option is not used (and deprecated). To take part in a Spring transaction, use the Spring JDBC Component.

Generated keys

If you insert data using SQL INSERT, then the RDBMS may support auto generated keys. You can instruct the JDBC producer to return the generated keys in headers.
To do that set the header CamelRetrieveGeneratedKeys=true. Then the generated keys will be provided as headers with the keys listed in the table above.

The generated keys in the header CamelGeneratedKeysRows are a List of Map objects with the key columns, whatever the outputClass and readSize of the endpoint.

Using named parameters

In the given route below, we want to get all the projects from the projects table. Notice the SQL query has two named parameters, :?lic and :?min. Camel will then look up these parameters from the message headers. Notice in the example above we set two headers with constant value for the named parameters:

  • Java

  • XML

  • YAML

from("direct:projects")
    .setHeader("lic", constant("ASF"))
    .setHeader("min", constant(123))
    .setBody(constant("select * from projects where license = :?lic and id > :?min order by id"))
    .to("jdbc:myDataSource?useHeadersAsParameters=true");
<route>
    <from uri="direct:projects"/>
    <setHeader name="lic">
        <constant>ASF</constant>
    </setHeader>
    <setHeader name="min">
        <constant>123</constant>
    </setHeader>
    <setBody>
        <constant>select * from projects where license = :?lic and id &gt; :?min order by id</constant>
    </setBody>
    <to uri="jdbc:myDataSource?useHeadersAsParameters=true"/>
</route>
- route:
    from:
      uri: direct:projects
      steps:
        - setHeader:
            name: lic
            constant: ASF
        - setHeader:
            name: min
            constant: "123"
        - setBody:
            constant: "select * from projects where license = :?lic and id > :?min order by id"
        - to:
            uri: jdbc:myDataSource
            parameters:
              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. When CamelJdbcParameters is not a Map (such as the List of an earlier query with plain ? placeholders in the same route), the named parameters take their values from the message headers.

Using plain ? placeholders

A query with plain ? placeholders (and no named parameters) takes the values of the placeholders, in order, only from the CamelJdbcParameters header, as a java.util.List (a java.util.Map works too, with its values taken in the order of its entries, so use a LinkedHashMap). An object array works like a List, and any other value is the value of a query with one ? placeholder: a String is not split by comma, and a byte[] is one value. The other message headers are not used. When the header is not set, or has more or fewer values than the query has ? placeholders, the exchange fails.

Java-only: inline Processor that sets the List of the values
from("direct:projects")
    .process(exchange -> exchange.getIn().setHeader(JdbcConstants.JDBC_PARAMETERS, List.of("ASF", 123)))
    .setBody(constant("select * from projects where license = ? and id > ? order by id"))
    .to("jdbc:myDataSource?useHeadersAsParameters=true");

Noticing a dead or silent database

The JDBC component has no network timeout of its own: how long the producer waits for a database that stopped answering depends on the JDBC driver and the connection pool of the DataSource. The durations below describe how those libraries behave by default; they are approximate, not guarantees of Camel.

The common JDBC drivers have no read timeout by default. A statement on a connection that went silent (the database host is gone, or a firewall or NAT dropped the connection without a reset) waits in a socket read, with no error and nothing logged, until the operating system gives up on the connection: on Linux about 15 minutes when the request was not acknowledged, and never when it was and TCP keep-alive is off. Set the driver’s socket timeout, longer than your slowest statement, so the producer fails and the error handler can redeliver:

Driver Property Unit Default

PostgreSQL (pgjdbc)

socketTimeout

seconds

0 (no timeout)

MySQL Connector/J

socketTimeout

milliseconds

0 (no timeout)

MariaDB Connector/J

socketTimeout

milliseconds

0 (no timeout)

Microsoft SQL Server (mssql-jdbc)

socketTimeout

milliseconds

0 (no timeout)

Oracle (thin driver)

oracle.jdbc.ReadTimeout

milliseconds

not set (no timeout)

For example jdbc:postgresql://db:5432/orders?socketTimeout=30 in the JDBC URL, or the same property as a driver property of the pool.

After a socket timeout or a reset the connection is broken, and the pool must not hand it out again. HikariCP and the Agroal pool that Quarkus configures drop it by default; Agroal used directly needs a connection validator and an exception sorter. See Noticing a dead or silent database in the SQL component for the pool settings, Spring Boot and Quarkus properties, and starting while the database is down.

Examples

In the following example, we set up the DataSource that camel-jdbc requires. First we register our datasource in the Camel registry as testdb:

Java-only: programmatic DataSource registration using EmbeddedDatabaseBuilder
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
      .setType(EmbeddedDatabaseType.H2).addScript("sql/init.sql").build();

CamelContext context = ...
context.getRegistry().bind("testdb", db);

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:

  • Java

  • XML

  • YAML

from("direct:hello")
    .to("jdbc:testdb");
<route>
  <from uri="direct:hello"/>
  <to uri="jdbc:testdb"/>
</route>
- route:
    from:
      uri: direct:hello
      steps:
        - to:
            uri: jdbc:testdb

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:

Java-only: using ProducerTemplate to send an exchange to the endpoint
Endpoint endpoint = context.getEndpoint("direct:hello");
Exchange exchange = endpoint.createExchange();
// then we set the SQL on the in body
exchange.getMessage().setBody("select * from customer order by ID");
// now we send the exchange to the endpoint, and receive the response from Camel
Exchange out = template.send(endpoint, exchange);

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:

  • Java

  • XML

  • YAML

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
// the StreamList option allows streaming the result of the query without creating a List of rows
// and notice we also enable streaming mode on the splitter
.to("jdbc:testdb?outputType=StreamList")
  .split(body()).streaming()
  .to("mock:result");
<route>
  <from uri="direct:hello"/>
  <to uri="jdbc:testdb?outputType=StreamList"/>
  <split streaming="true">
    <simple>${body}</simple>
    <to uri="mock:result"/>
  </split>
</route>
- route:
    from:
      uri: direct:hello
      steps:
        - to:
            uri: jdbc:testdb
            parameters:
              outputType: StreamList
        - split:
            expression:
              simple:
                expression: "${body}"
            streaming: true
            steps:
              - to:
                  uri: mock:result

The result set and the connection stay open until the exchange is done. With resetAutoCommit=true (the default), the transaction of the statement ends then too: it is committed when the exchange completes, or rolled back when it fails. A commit that fails at that time is logged at WARN and does not fail the exchange, which is already complete. For a statement with side effects that returns rows (such as an INSERT or DELETE with RETURNING), the route then reports success (and a consumer such as JMS acknowledges its message) although the change is not committed: use another output type, such as SelectList, when a failed commit must fail the exchange.

Whether the rows are loaded as needed depends on the JDBC driver. For example, the PostgreSQL driver fetches statement.fetchSize rows at a time only when auto-commit is off (as resetAutoCommit=true sets it); otherwise it loads all the rows when the statement is executed.

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:

  • Java

  • XML

  • YAML

from("timer://foo?period=60000")
    .setBody(constant("select * from customer"))
    .to("jdbc:testdb")
    .to("activemq:queue:customers");
<route>
    <from uri="timer://foo?period=60000"/>
    <setBody>
        <constant>select * from customer</constant>
    </setBody>
    <to uri="jdbc:testdb"/>
    <to uri="activemq:queue:customers"/>
</route>
- route:
    from:
      uri: timer://foo
      parameters:
        period: "60000"
      steps:
        - setBody:
            constant: "select * from customer"
        - to:
            uri: jdbc:testdb
        - to:
            uri: activemq:queue:customers

Move Data Between Data Sources

A common use case is to query for data, process it and move it to another data source (ETL operations). In the following example, we retrieve new customer records from the source table every hour, filter/transform them and move them to a destination table:

Java-only: ETL route using inline Processor to filter and transform results
from("timer://MoveNewCustomersEveryHour?period=3600000")
    .setBody(constant("select * from customer where create_time > (sysdate-1/24)"))
    .to("jdbc:testdb")
    .split(body())
        .process(new MyCustomerProcessor()) //filter/transform results as needed
        .setBody(simple("insert into processed_customer values('${body[ID]}','${body[NAME]}')"))
        .to("jdbc:testdb");

Secret Rotation

The JDBC component implements SecretRotationAware. When a secret rotation event is triggered (e.g. by a vault provider), the component evicts stale connections from its connection pools. This covers the component-level DataSource as well as any DataSources resolved by active endpoints (e.g. jdbc:myDs), with identity-based deduplication so each pool is evicted at most once.

When a camel.component.jdbc.* option uses a placeholder value, Camel Main replaces the component instance on reload. In that case the endpoint DataSources are matched against the old component instance and are skipped; only the component-level dataSource (if configured directly on the new component) is evicted.
The eviction is triggered by any context reload (vault rotation, JMX onReload operation, camel cmd reload, load-on-demand), not only by vault secret rotation events. These pools are often shared with non-Camel code, so applications that trigger context reloads for other reasons should be aware that pool connections will be evicted.

Currently HikariCP and Agroal (Quarkus default) pools are supported for active eviction. HikariCP pools are evicted via softEvictConnections() called through getHikariPoolMXBean() via reflection — JMX registration (registerMbeans=true) is not required. Agroal pools are evicted via flush(GRACEFUL) called on AgroalDataSource via reflection. Other pool implementations are not actively evicted — existing connections will be replaced as they expire or are validated by the pool.

The pool eviction uses reflection to avoid compile-time dependencies on pool libraries. In GraalVM native mode (e.g. Quarkus native), the reflected classes and methods need to be registered for reflection: HikariDataSource.getHikariPoolMXBean(), HikariPoolMXBean.softEvictConnections() for HikariCP, and AgroalDataSource.flush(FlushMode) for Agroal.
The eviction only closes existing connections — it does not update the pool’s credentials. For pools configured with a static password (e.g. Spring Boot spring.datasource.password), the pool will re-open connections using the old credentials. This feature works out of the box only with pools that resolve credentials dynamically, such as HikariCredentialsProvider (HikariCP 7.0 or later), the AWS JDBC wrapper secrets plugin, or a custom DataSource that fetches credentials from a vault at connect time.