Camel Components

Spring JDBC

Since Camel 3.10

Only producer is supported

The Spring JDBC component is an extension of the JDBC component with one additional feature to integrate with Spring Transaction Manager.

For general use of this component, see the JDBC Component.

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

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

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 Spring 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 Spring JDBC endpoint is configured using URI syntax:

spring-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 Spring 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 Spring 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

The message body is the SQL to run, as with the JDBC component. The component gets its connections through Spring’s DataSourceUtils, so it uses the connection of a Spring-managed transaction. Set resetAutoCommit to false in that case: by default, the component commits and closes the connection itself.

- route:
    from:
      uri: direct:orders
      steps:
        - setBody:
            expression:
              constant:
                expression: "select id, item, amount from orders where amount > 100"
        - to:
            uri: spring-jdbc:myDataSource
        - log:
            message: "Found ${body.size} orders: ${body}"