55.10. サンプル
次の例では、camel-jdbc に必要な DataSource をセットアップします。まず、データソースを Camel レジストリーに testdb として登録します。
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.DERBY).addScript("sql/init.sql").build();
CamelContext context = ...
context.getRegistry().bind("testdb", db);
次に、JDBC コンポーネントにルーティングするルートを設定して、SQL が実行されるようにします。前のステップでバインドされた testdb データソースを参照する方法に注意してください。
from("direct:hello")
.to("jdbc:testdb");
エンドポイントを作成し、IN メッセージの本文に SQL クエリーを追加して、エクスチェンジを送信します。クエリーの結果は、OUT ボディーで返されます。
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 receives the response from Camel
Exchange out = template.send(endpoint, exchange);
一度に ResultSet 全体ではなく、行を 1 つずつ処理する場合は、次のようなスプリッター EIP を使用する必要があります。
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 to stream 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");