이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Chapter 50. 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.
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
This component can not be used as a Transactional Client. If you need transaction support in your route, you should use the SQL component instead.

URI format

jdbc:dataSourceName[?options]
Copy to Clipboard Toggle word wrap
This component only supports producer endpoints.
You can append query options to the URI in the following format, ?option=value&option=value&...

Options

Expand
Name Default Value Description
readSize 0 The default maximum number of rows that can be read by a polling query.
statement.<xxx> null Apache Camel 2.1: Sets additional options on the java.sql.Statement that is used behind the scenes to execute the queries. For instance, statement.maxRows=10. For detailed documentation, see the java.sql.Statement javadoc documentation.
useJDBC4ColumnNameAndLabelSemantics true 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).
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'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.

Result

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
This component fetches ResultSetMetaData to be able to return the column name as the key in the Map.

Message Headers

Expand
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.

Generated keys

Available as of Camel 2.10
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.
You can see more details in this unit test.

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", db);
return reg;
Copy to Clipboard Toggle word wrap
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");
}
Copy to Clipboard Toggle word wrap
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-->
<jdbc:embedded-database id="testdb" type="DERBY">
	<jdbc:script location="classpath:sql/init.sql"/>
</jdbc:embedded-database>
Copy to Clipboard Toggle word wrap
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());
List<Map<String, Object>> data = out.getOut().getBody(List.class);
assertNotNull(data);
assertEquals(3, data.size());
Map<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"));
Copy to Clipboard Toggle word wrap
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");

Copy to Clipboard Toggle word wrap

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");
Copy to Clipboard Toggle word wrap
See also:
맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat