Apache Camel JDBC and SQL components: queries, polling and transactions

Camel talks to relational databases through two components: jdbc, which runs the SQL in the message body, and sql, which runs a fixed statement with parameters from the message. This page explains how each one works, then runs every important case against a real database, from SQL injection and batch inserts to polling, transactions and duplicate detection.

Contents

Two components for SQL: jdbc and sql

Camel has two main components for relational databases. Both have been part of Camel since its early releases, and they work in different ways:

  • jdbc (camel-jdbc): the message body is the SQL statement. The endpoint jdbc:shopDb names only the DataSource, looked up in the registry. The component takes a connection, runs whatever SQL the body holds with plain JDBC, and puts the result in the body. It is a producer only.
  • sql (camel-sql): the SQL statement is in the endpoint URI, and parameters come from the message, by position (#) or by name (:#name). It runs on Spring's JdbcTemplate, so it joins Spring transactions. It also works as a consumer that polls a table, and it can run batch inserts.

The difference decides where the SQL comes from. With jdbc, the route builds the statement at runtime, which is flexible and easy to get wrong, because values pasted into SQL text allow SQL injection. With sql, the statement is fixed when the route is written, and only parameter values change.

Camel's database components
ComponentSQL fromConsumerBest for
jdbcThe message bodyNoSQL that must be built at runtime, or statements passed through from elsewhere
sqlThe URI, or a file with classpath:Yes, pollingMost routes: fixed statements, named parameters, batches, transactions
sql-storedThe URI, as a procedure call templateNoCalling stored procedures with IN and OUT parameters
jpaEntities and JPQLYes, pollingRoutes that already use a JPA model

Both components return rows the same way: a List of Maps, one map per row, from column name to value. The examples are complete programs for Camel 4.23 on Java 21, run against an in-memory H2 2.4 database through H2's own JdbcDataSource, with Camel's logging turned off. camel-sql brings Spring JDBC 7.0 with it; the transaction example also needs camel-spring. This page does not run sql-stored or jpa.

The jdbc component: the body is the SQL

A small product table is enough to see every kind of result the jdbc component returns: an update count, rows as maps, a single value and rows mapped to a JavaBean:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;

public class JdbcBasics {

    // outputClass needs a JavaBean: a public no-argument constructor and setters
    public static class Product {
        private int id;
        private String name;
        private BigDecimal unitPrice;

        public void setId(int id) {
            this.id = id;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setUnitPrice(BigDecimal unitPrice) {
            this.unitPrice = unitPrice;
        }

        @Override
        public String toString() {
            return "Product[id=" + id + ", name=" + name + ", unitPrice=" + unitPrice + "]";
        }
    }

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1");

        CamelContext context = new DefaultCamelContext();
        context.getRegistry().bind("shopDb", dataSource);
        context.start();
        ProducerTemplate template = context.createProducerTemplate();

        // with the jdbc component, the message body is the SQL statement
        template.requestBody("jdbc:shopDb", "CREATE TABLE product (id INT PRIMARY KEY,"
                + " name VARCHAR(30), unit_price DECIMAL(6,2))");
        Exchange insert = template.request("jdbc:shopDb", e -> e.getMessage().setBody(
                "INSERT INTO product VALUES (1, 'book', 12.50), (2, 'pen', 1.20),"
                        + " (3, 'lamp', 30.00)"));
        System.out.println("INSERT: CamelJdbcUpdateCount = "
                + insert.getMessage().getHeader("CamelJdbcUpdateCount"));

        Exchange select = template.request("jdbc:shopDb", e -> e.getMessage().setBody(
                "SELECT id, name, unit_price FROM product ORDER BY id"));
        List<?> rows = select.getMessage().getBody(List.class);
        System.out.println("SELECT: body type " + rows.getClass().getSimpleName()
                + " of " + rows.get(0).getClass().getSimpleName()
                + ", CamelJdbcRowCount = " + select.getMessage().getHeader("CamelJdbcRowCount"));
        rows.forEach(row -> System.out.println("  " + row));
        System.out.println("  columns: " + select.getMessage().getHeader("CamelJdbcColumnNames"));

        Map<?, ?> first = (Map<?, ?>) rows.get(0);
        System.out.println("  get(\"name\") = " + first.get("name")
                + ", get(\"NAME\") = " + first.get("NAME"));

        Object one = template.requestBody("jdbc:shopDb?outputType=SelectOne",
                "SELECT name FROM product WHERE id = 3");
        System.out.println("outputType=SelectOne, one column: " + one
                + " (" + one.getClass().getSimpleName() + ")");
        List<?> products = template.requestBody(
                "jdbc:shopDb?outputClass=JdbcBasics$Product",
                "SELECT * FROM product WHERE unit_price > 10 ORDER BY id", List.class);
        System.out.println("outputClass=JdbcBasics$Product:");
        products.forEach(product -> System.out.println("  " + product));
        context.close();
    }
}
Output
INSERT: CamelJdbcUpdateCount = 3
SELECT: body type ArrayList of LinkedHashMap, CamelJdbcRowCount = 3
  {ID=1, NAME=book, UNIT_PRICE=12.50}
  {ID=2, NAME=pen, UNIT_PRICE=1.20}
  {ID=3, NAME=lamp, UNIT_PRICE=30.00}
  columns: [ID, NAME, UNIT_PRICE]
  get("name") = null, get("NAME") = book
outputType=SelectOne, one column: lamp (String)
outputClass=JdbcBasics$Product:
  Product[id=1, name=book, unitPrice=12.50]
  Product[id=3, name=lamp, unitPrice=30.00]
  • The INSERT set the CamelJdbcUpdateCount header to 3, the number of rows changed. The body after an update is not useful.
  • The SELECT returned an ArrayList of LinkedHashMap, with CamelJdbcRowCount 3 and the column names in CamelJdbcColumnNames. Each map keeps the columns in query order.
  • The keys are ID, NAME and UNIT_PRICE, in upper case, because H2 stores unquoted names in upper case. get("name") returned null. PostgreSQL returns lower case, so code that reads row maps by key can break when the database changes. Use column aliases, or map rows to a class.
  • outputType=SelectOne with a single-column result returned the value itself: the String lamp, not a list or a map.
  • outputClass mapped each row to a Product. The default BeanRowMapper lowers the column name and drops underscores, so UNIT_PRICE matched setUnitPrice. The class name is the binary name, JdbcBasics$Product, because it is nested, and the class needs a no-argument constructor and setters: a record does not work here.

DDL statements such as CREATE TABLE run the same way, which the program uses to set up the table. By default the component turns auto-commit off, runs the statement, commits, and restores auto-commit (resetAutoCommit=true).

Parameters, and the SQL injection trap

A lookup by user name is the classic case for SQL injection. This program runs one query four ways, with a normal name and with the input nobody' OR '1'='1:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;

public class Parameters {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:mem:users;DB_CLOSE_DELAY=-1");

        CamelContext context = new DefaultCamelContext();
        context.getRegistry().bind("usersDb", dataSource);
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                // unsafe: the header is pasted into the SQL text
                from("direct:concatenated")
                        .setBody(simple("SELECT name FROM app_user"
                                + " WHERE name = '${header.name}' ORDER BY name"))
                        .to("jdbc:usersDb");
                // jdbc component: :?name placeholders filled from headers
                from("direct:jdbcParams")
                        .setBody(constant("SELECT name FROM app_user"
                                + " WHERE name = :?name ORDER BY name"))
                        .to("jdbc:usersDb?useHeadersAsParameters=true");
                // sql component: the SQL is in the URI, :#name comes from the header
                from("direct:sqlParams")
                        .to("sql:SELECT name FROM app_user WHERE name = :#name ORDER BY name"
                                + "?dataSource=#usersDb");
                // sql component: :#${...} takes any Simple expression
                from("direct:sqlExpression")
                        .to("sql:SELECT name FROM app_user WHERE role = :#${body[role]}"
                                + " ORDER BY name?dataSource=#usersDb");
            }
        });
        context.start();
        ProducerTemplate template = context.createProducerTemplate();
        template.requestBody("sql:CREATE TABLE app_user (name VARCHAR(20), role VARCHAR(10))"
                + "?dataSource=#usersDb", (Object) null);
        template.requestBody("sql:INSERT INTO app_user VALUES ('alice', 'admin'),"
                + " ('bob', 'user'), ('carol', 'user')?dataSource=#usersDb", (Object) null);

        String attack = "nobody' OR '1'='1";
        for (String route : new String[] {"concatenated", "jdbcParams", "sqlParams"}) {
            System.out.println(route + ":");
            System.out.println("  name=alice  -> " + template.requestBodyAndHeader(
                    "direct:" + route, null, "name", "alice"));
            System.out.println("  name=" + attack + " -> " + template.requestBodyAndHeader(
                    "direct:" + route, null, "name", attack));
        }
        System.out.println("sqlExpression with body {role=user}: "
                + template.requestBody("direct:sqlExpression", Map.of("role", "user")));
        context.close();
    }
}
Output
concatenated:
  name=alice  -> [{NAME=alice}]
  name=nobody' OR '1'='1 -> [{NAME=alice}, {NAME=bob}, {NAME=carol}]
jdbcParams:
  name=alice  -> [{NAME=alice}]
  name=nobody' OR '1'='1 -> []
sqlParams:
  name=alice  -> [{NAME=alice}]
  name=nobody' OR '1'='1 -> []
sqlExpression with body {role=user}: [{NAME=bob}, {NAME=carol}]
  • concatenated built the SQL with simple(), pasting the header into the text. For alice it worked. For the attack, the quote in the input ended the string, the statement became WHERE name = 'nobody' OR '1'='1', and all three users came back.
  • jdbcParams used the jdbc component with useHeadersAsParameters=true and a :?name placeholder. Camel sent the header as a PreparedStatement parameter, so the attack string was compared as a value, and no user has that name: the result was empty.
  • sqlParams used the sql component's :#name, which also becomes a PreparedStatement parameter, with the same safe result.
  • :#${body[role]} takes any Simple expression, here a value from a Map body, so parameters can come from the body, headers or exchange properties.

Named parameters are looked up in the body first, if it is a Map, then in the headers. The sql component also accepts # for positional parameters, filled from the body in order: a List, an array, or a comma-separated String. Camel 4.23 adds one more guard: the CamelSqlQuery header can replace the endpoint's statement only when the endpoint sets allowQueryFromHeader=true, because a header from outside the route could otherwise run any SQL.

Batch inserts and other sql producer options

Inserting many rows one statement at a time costs one round trip and one statement execution per row. With batch=true, the sql component sends all rows in one JDBC batch. This program inserts 20,000 sensor readings both ways, three times each, then shows two other producer options:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;

public class SqlBatch {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:mem:metrics;DB_CLOSE_DELAY=-1");

        CamelContext context = new DefaultCamelContext();
        // with a single DataSource in the registry, sql: endpoints find it without a name
        context.getRegistry().bind("metricsDb", dataSource);
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:oneByOne")
                        .split(body())
                            .to("sql:INSERT INTO reading (sensor, celsius)"
                                    + " VALUES (:#sensor, :#celsius)")
                        .end();
                from("direct:batch")
                        .to("sql:INSERT INTO reading (sensor, celsius)"
                                + " VALUES (:#sensor, :#celsius)?batch=true");
                from("direct:maxPerSensor")
                        .to("sql:SELECT sensor, MAX(celsius) AS top FROM reading"
                                + " GROUP BY sensor ORDER BY sensor"
                                + "?outputHeader=maxima")
                        .setBody(simple("${body} (body kept), maxima = ${header.maxima}"));
            }
        });
        context.start();
        ProducerTemplate template = context.createProducerTemplate();
        template.requestBody("sql:CREATE TABLE reading (id INT AUTO_INCREMENT PRIMARY KEY,"
                + " sensor VARCHAR(10), celsius DOUBLE)", (Object) null);

        List<Map<String, Object>> readings = new ArrayList<>();
        for (int i = 0; i < 20000; i++) {
            readings.add(Map.of("sensor", "s" + (i % 4), "celsius", 15.0 + i % 10));
        }
        long bestOneByOne = Long.MAX_VALUE;
        long bestBatch = Long.MAX_VALUE;
        Exchange batch = null;
        for (int round = 1; round <= 3; round++) {
            long start = System.nanoTime();
            template.requestBody("direct:oneByOne", readings);
            bestOneByOne = Math.min(bestOneByOne, System.nanoTime() - start);
            start = System.nanoTime();
            batch = template.request("direct:batch", e -> e.getMessage().setBody(readings));
            bestBatch = Math.min(bestBatch, System.nanoTime() - start);
        }
        System.out.println("batch CamelSqlUpdateCount = "
                + batch.getMessage().getHeader("CamelSqlUpdateCount"));
        System.out.printf("20,000 rows, best of 3: one by one %d ms, batch %d ms%n",
                bestOneByOne / 1000000, bestBatch / 1000000);
        System.out.println("rows in table: " + template.requestBody(
                "sql:SELECT COUNT(*) FROM reading?outputType=SelectOne", (Object) null));
        System.out.println(template.requestBody("direct:maxPerSensor", "original body"));

        Exchange insert = template.request("sql:INSERT INTO reading (sensor, celsius)"
                + " VALUES ('s9', 99.5)", e -> e.getMessage().setHeader(
                        "CamelSqlRetrieveGeneratedKeys", true));
        System.out.println("generated keys: "
                + insert.getMessage().getHeader("CamelSqlGeneratedKeyRows"));
        context.close();
    }
}
Output
batch CamelSqlUpdateCount = 20000
20,000 rows, best of 3: one by one 1288 ms, batch 141 ms
rows in table: 120000
original body (body kept), maxima = [{SENSOR=s0, TOP=23.0}, {SENSOR=s1, TOP=24.0}, {SENSOR=s2, TOP=23.0}, {SENSOR=s3, TOP=24.0}]
generated keys: [{ID=120001}]
  • With batch=true and a List of Maps as the body, one exchange inserted all 20,000 rows, and CamelSqlUpdateCount reported 20000.
  • The batch was several times faster than splitting the list and inserting each row. This is a rough comparison on a 2-core Xeon VM with an in-memory database, where each statement costs no network round trip. Across a network, the gap is usually larger. Across repeated runs, the ratio was between 5 and 10.
  • The table holds 120,000 rows: three timed runs of each method, 20,000 rows per run.
  • outputHeader=maxima put the query result in a header and left the body unchanged, which is useful when a route needs lookup data next to its original message.
  • With the CamelSqlRetrieveGeneratedKeys header set to true, the insert returned the key that the database generated, ID=120001, in CamelSqlGeneratedKeyRows.

The registry held a single DataSource, so the sql endpoints found it without a dataSource option. With two or more, name the one to use with dataSource=#name, as the previous example did. By default a batch runs with auto-commit off and commits once at the end (batchAutoCommitDisabled=true), which is part of why it is fast.

Polling a table with the sql consumer

Used in from(), the sql component runs its query on a schedule and sends one exchange per row. A common use is the outbox pattern: the application writes events to a table, and a route publishes them. Five events, one of which fails, show how the consumer marks rows and splits work into polls:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;

public class SqlPolling {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:mem:outbox;DB_CLOSE_DELAY=-1");

        CamelContext context = new DefaultCamelContext();
        context.getRegistry().bind("outboxDb", dataSource);
        ProducerTemplate setup = context.createProducerTemplate();
        context.start();
        setup.requestBody("sql:CREATE TABLE outbox (id INT PRIMARY KEY, event VARCHAR(30),"
                + " status VARCHAR(10))", (Object) null);
        setup.requestBody("sql:INSERT INTO outbox VALUES (1, 'order placed', 'NEW'),"
                + " (2, 'BROKEN', 'NEW'), (3, 'order shipped', 'NEW'),"
                + " (4, 'order paid', 'NEW'), (5, 'order closed', 'NEW')", (Object) null);

        NotifyBuilder fiveRows = new NotifyBuilder(context).fromRoute("outbox-poller")
                .whenDone(5).create();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("sql:SELECT * FROM outbox WHERE status = 'NEW' ORDER BY id"
                        + "?initialDelay=0&delay=200&maxMessagesPerPoll=2"
                        + "&onConsume=UPDATE outbox SET status = 'SENT' WHERE id = :#id"
                        + "&onConsumeFailed=UPDATE outbox SET status = 'FAILED' WHERE id = :#id")
                        .routeId("outbox-poller")
                        .process(e -> {
                            Map<?, ?> row = e.getMessage().getBody(Map.class);
                            System.out.println("poll item " + (e.getProperty(
                                    "CamelBatchIndex", Integer.class) + 1) + "/"
                                    + e.getProperty("CamelBatchSize") + ": " + row);
                            if (row.get("EVENT").equals("BROKEN")) {
                                throw new IllegalStateException("cannot publish");
                            }
                        });
            }
        });
        System.out.println("all rows handled: " + fiveRows.matches(10, TimeUnit.SECONDS));
        Thread.sleep(500); // a few more polls, which find nothing
        context.getRouteController().stopRoute("outbox-poller");

        List<?> rows = setup.requestBody("sql:SELECT id, status FROM outbox ORDER BY id",
                (Object) null, List.class);
        System.out.println("table afterwards:");
        rows.forEach(row -> System.out.println("  " + row));

        System.out.println("Without onConsume:");
        NotifyBuilder threeTimes = new NotifyBuilder(context).fromRoute("no-mark")
                .whenDone(3).create();
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("sql:SELECT id FROM outbox WHERE id = 1"
                        + "?initialDelay=0&delay=200&repeatCount=3")
                        .routeId("no-mark")
                        .process(e -> System.out.println("  read " + e.getMessage().getBody()));
            }
        });
        System.out.println("  the same row was delivered 3 times: "
                + threeTimes.matches(5, TimeUnit.SECONDS));
        context.close();
    }
}
Output
poll item 1/2: {ID=1, EVENT=order placed, STATUS=NEW}
poll item 2/2: {ID=2, EVENT=BROKEN, STATUS=NEW}
poll item 1/2: {ID=3, EVENT=order shipped, STATUS=NEW}
poll item 2/2: {ID=4, EVENT=order paid, STATUS=NEW}
poll item 1/1: {ID=5, EVENT=order closed, STATUS=NEW}
all rows handled: true
table afterwards:
  {ID=1, STATUS=SENT}
  {ID=2, STATUS=FAILED}
  {ID=3, STATUS=SENT}
  {ID=4, STATUS=SENT}
  {ID=5, STATUS=SENT}
Without onConsume:
  read {ID=1}
  read {ID=1}
  read {ID=1}
  the same row was delivered 3 times: true
  • maxMessagesPerPoll=2 limited each poll to two rows, so the five rows came in polls of 2, 2 and 1, numbered with the CamelBatchIndex and CamelBatchSize exchange properties.
  • After each row succeeded, onConsume ran UPDATE ... SET status = 'SENT' WHERE id = :#id, with :#id taken from the row itself. The next poll's WHERE status = 'NEW' no longer matched it.
  • Row 2 threw an exception, so onConsumeFailed marked it FAILED instead. Without that option, it would stay NEW and be read again on every poll.
  • The last part polls with no onConsume at all. The same row was delivered three times, once per poll; repeatCount=3 stopped the scheduler after three polls so that the output is the same on every run.

The consumer marks each row only after the route finishes, so a crash between processing and marking delivers the row again on restart. Routes that publish from a table should therefore be safe to repeat, or use the idempotent repository shown below. To read the whole result as one List in a single exchange, set useIterator=false.

Transactions across several statements

Two statements in a route are two separate transactions unless the route says otherwise. A money transfer shows why that matters: credit Bob, then debit Alice, where a check constraint refuses a negative balance, so the debit fails when Alice cannot pay:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spring.spi.SpringTransactionPolicy;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

public class Transacted {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:mem:bank;DB_CLOSE_DELAY=-1");
        DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource);

        CamelContext context = new DefaultCamelContext();
        context.getRegistry().bind("bankDb", dataSource);
        context.getRegistry().bind("required", new SpringTransactionPolicy(txManager));
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                // CHECK (balance >= 0) makes the second statement fail when funds are short
                from("direct:plain")
                        .to("sql:UPDATE account SET balance = balance + :#amount"
                                + " WHERE name = 'bob'")
                        .to("sql:UPDATE account SET balance = balance - :#amount"
                                + " WHERE name = 'alice'");
                from("direct:transacted")
                        .transacted("required")
                        .to("sql:UPDATE account SET balance = balance + :#amount"
                                + " WHERE name = 'bob'")
                        .to("sql:UPDATE account SET balance = balance - :#amount"
                                + " WHERE name = 'alice'");
            }
        });
        context.start();
        ProducerTemplate template = context.createProducerTemplate();
        template.requestBody("sql:CREATE TABLE account (name VARCHAR(10) PRIMARY KEY,"
                + " balance INT CHECK (balance >= 0))", (Object) null);

        for (String route : new String[] {"plain", "transacted"}) {
            template.requestBody("sql:DELETE FROM account", (Object) null);
            template.requestBody("sql:INSERT INTO account VALUES ('alice', 50), ('bob', 0)",
                    (Object) null);
            System.out.println("direct:" + route + ", alice sends bob 80 but has only 50:");
            try {
                template.requestBodyAndHeader("direct:" + route, null, "amount", 80);
            } catch (Exception e) {
                Throwable root = e;
                while (root.getCause() != null) {
                    root = root.getCause();
                }
                System.out.println("  failed: " + root.getClass().getSimpleName());
            }
            System.out.println("  balances: " + template.requestBody(
                    "sql:SELECT name, balance FROM account ORDER BY name", (Object) null));
        }
        context.close();
    }
}
Output
direct:plain, alice sends bob 80 but has only 50:
  failed: JdbcSQLIntegrityConstraintViolationException
  balances: [{NAME=alice, BALANCE=50}, {NAME=bob, BALANCE=80}]
direct:transacted, alice sends bob 80 but has only 50:
  failed: JdbcSQLIntegrityConstraintViolationException
  balances: [{NAME=alice, BALANCE=50}, {NAME=bob, BALANCE=0}]
  • On direct:plain, the credit committed on its own before the debit failed. Bob now has 80 and Alice still has 50: money was created.
  • On direct:transacted, transacted("required") started a Spring transaction before the first statement. Both sql endpoints ran on the connection bound to that transaction, and the failure rolled back the credit, so the balances are unchanged at 50 and 0.
  • Both routes failed with H2's JdbcSQLIntegrityConstraintViolationException, the root cause the program printed. Camel and Spring wrap it in their own exceptions on the way out.

transacted() needs a TransactedPolicy. Here it is a SpringTransactionPolicy from camel-spring, around a DataSourceTransactionManager, bound under the name required. A plain transacted(), with no name, also works when the registry holds a single transaction manager, which is the usual case in a Spring Boot application. The transaction belongs to the thread, so a step that moves to another thread, such as seda: or a parallel splitter, leaves it. The Spring @Transactional page explains the same thread rule in Spring itself.

Skipping duplicates with a database idempotent repository

A message can arrive twice: a retry, a redelivered queue message, or a polled row read again after a crash. The Idempotent Consumer pattern remembers each message id and drops repeats. With JdbcMessageIdRepository from camel-sql, the ids live in a table, so they survive restarts and can be shared by several nodes. This program sends payments with a duplicate id, then does it again in a second context:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.processor.idempotent.jdbc.JdbcMessageIdRepository;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;

public class IdempotentRepo {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:mem:payments;DB_CLOSE_DELAY=-1");

        for (int run = 1; run <= 2; run++) {
            // a new CamelContext each time stands for a restart, or a second node
            CamelContext context = new DefaultCamelContext();
            JdbcMessageIdRepository repo = new JdbcMessageIdRepository(dataSource, "payments");
            context.addRoutes(new RouteBuilder() {
                @Override
                public void configure() {
                    from("direct:payment")
                            .idempotentConsumer(header("paymentId"), repo)
                            .process(e -> System.out.println("  charged "
                                    + e.getMessage().getHeader("paymentId")));
                }
            });
            context.start();
            ProducerTemplate template = context.createProducerTemplate();
            System.out.println("run " + run + ":");
            for (String id : new String[] {"P-1", "P-2", "P-1", "P-" + (run + 2)}) {
                template.sendBodyAndHeader("direct:payment", "amount=10", "paymentId", id);
            }
            context.close();
        }

        CamelContext reader = new DefaultCamelContext();
        reader.getRegistry().bind("paymentsDb", dataSource);
        reader.start();
        System.out.println("CAMEL_MESSAGEPROCESSED: " + reader.createProducerTemplate()
                .requestBody("sql:SELECT processorName, messageId FROM CAMEL_MESSAGEPROCESSED"
                        + " ORDER BY messageId", (Object) null));
        reader.close();
    }
}
Output
run 1:
  charged P-1
  charged P-2
  charged P-3
run 2:
  charged P-4
CAMEL_MESSAGEPROCESSED: [{PROCESSORNAME=payments, MESSAGEID=P-1}, {PROCESSORNAME=payments, MESSAGEID=P-2}, {PROCESSORNAME=payments, MESSAGEID=P-3}, {PROCESSORNAME=payments, MESSAGEID=P-4}]
  • In run 1, P-1 arrived twice and was charged once. P-2 and P-3 were new.
  • Run 2 used a new CamelContext and a new repository object, but the same table. P-1 and P-2 were already recorded, so only P-4 was charged.
  • The repository created the table CAMEL_MESSAGEPROCESSED on first use, with the processor name, payments, and the message id as a composite primary key, plus a createdAt timestamp that the query left out.

The primary key also protects against two nodes processing the same id at the same moment: only one insert can succeed. Old entries are never removed by Camel, so delete rows by createdAt once duplicates are no longer possible. The Idempotent Consumer pattern on files is shown on the Camel File component page.

Choosing a database approach

Common situations and what fits them
SituationWhat to use
A fixed query with values from the messagesql: with :#name parameters
SQL that must be built at runtimejdbc: with useHeadersAsParameters=true for every value
Values from user inputParameters only, never simple() inside the SQL text
Thousands of insertssql: with batch=true and a List body
Reading new rows from a tableThe sql consumer with onConsume and onConsumeFailed
Several statements that must succeed togethertransacted() with sql: endpoints
Messages that may arrive twiceidempotentConsumer with JdbcMessageIdRepository
Rows as typed objectsoutputClass with a JavaBean
Stored proceduressql-stored:

The traps to remember are SQL text built from message values, column names whose case depends on the database, polled rows that are never marked, and statements that commit one by one outside a transaction. For the JDBC API underneath, see JDBC transactions and batch updates; for Camel in a Spring Boot application, where the DataSource comes from spring.datasource.*, see Camel with Spring Boot.