DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Generate Random Test Data in PostgreSQL
  • Database Connection Pooling at Scale: PgBouncer + Multi-Tenant Postgres (10K Concurrent Connections)
  • Why PostgreSQL Vacuum Matters More Than You Think
  • No More ETL: How Lakebase Combines OLTP, Analytics in One Platform

Trending

  • 5 AI Security Incidents That Broke Things in Production (and What They Have in Common)
  • Alternative Structured Concurrency
  • GenAI Implementation Isn't Magic — It’s a Lifecycle
  • Slopsquatting: Building a Scanner That Catches AI-Hallucinated Packages Before They Reach Production
  1. DZone
  2. Data Engineering
  3. Databases
  4. Connecting a PostgreSQL Database With Apache Camel

Connecting a PostgreSQL Database With Apache Camel

The jdbc: and sql: components in Apache Camel are similar, but vastly different. Let's see how you can use them to connect to a Postgres database.

By 
Jitendra Bafna user avatar
Jitendra Bafna
·
Dec. 26, 17 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
30.2K Views

Join the DZone community and get the full member experience.

Join For Free

The jdbc: component allows you to access a database using JDBC, whereas the Select query and operations (UPDATE, INSERT, DELETE etc.) send messages in bodies.

The sql: component allows you to work with databases using JDBC queries. The difference between this component and the JDBC component is that, with SQL, the query is a property of the endpoint, and it uses message payloads as parameters passed to the query.

Connecting to a Postgres Database Using the jdbc: Component

We will define the route that will be using JDBC components to access our database and will use an example of inserting data into a table. In this case, we will define the processor to build the insert query and pass it to the message body.

Adding POM dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.learncamel</groupId>
    <artifactId>learncamel-activemq2db</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-core</artifactId>
        <version>2.19.2</version>
    </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-sql</artifactId>
            <version>2.19.2</version>
        </dependency>
    <!-- camel-jms dependency -->
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-jms</artifactId>
        <version>2.19.2</version>
    </dependency>

    <!-- Logging Jars -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.12</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.12</version>
    </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <version>2.19.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jdbc</artifactId>
            <version>2.10.4</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4.1212</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.5.4</version>
        </dependency>
    </dependencies>
</project>


Defining the route:

package com.learncamel.route.jdbc;

import org.apache.camel.builder.RouteBuilder;

public class DBPostgresRoute extends RouteBuilder{
    public void configure() throws Exception {

        from("direct:dbInput")
                .to("log:?level=INFO&showBody=true")
                .process(new InsertProcessor())
                .to("jdbc:myDataSource");
    }
}


Defining the processor

package com.learncamel.route.jdbc;

import org.apache.camel.Exchange;

public class InsertProcessor implements org.apache.camel.Processor {
    public void process(Exchange exchange) throws Exception {
        String input = (String) exchange.getIn().getBody();
        System.out.println("Input to be persisted : " + input);
        String insertQuery = "INSERT INTO messages values ( '1','" + input+"')";
        System.out.println("Insert Query is : " + insertQuery);
        exchange.getIn().setBody(insertQuery);
    }
}


Defining CamelContext and DataSource

Camel context:

@Override
public CamelContext createCamelContext() {

    String url = "jdbc:postgresql://localhost:5432/localdb";
    DataSource dataSource = setupDataSource(url);

    SimpleRegistry registry = new SimpleRegistry();
    registry.put("myDataSource", dataSource);

    CamelContext context = new DefaultCamelContext(registry);
    // plug in a seda component, as we don't really need an embedded broker
    return context;
}


Simple data source:

    private static DataSource setupDataSource(String connectURI) {
        BasicDataSource ds = new BasicDataSource();
        ds.setUsername("postgres");
        ds.setDriverClassName("org.postgresql.Driver");
        ds.setPassword("sqlserver");
        ds.setUrl(connectURI);
        return ds;
    }
}


Below is the list of packages we need to add to your class:

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.commons.dbcp.BasicDataSource;


Connecting the Postgres Database Using the sql: Component

package com.learncamel.route.jdbc;

import org.apache.camel.builder.RouteBuilder;

public class DBPostgresRoute extends RouteBuilder{
    public void configure() throws Exception {

        from("direct:dbInput")
                .to("log:?level=INFO&showBody=true")
            .to("sql:select * from messages?dataSource=myDataSource")
                .to("log:?level=INFO&showBody=true");
    }
}


The dataSource value should be the same thing you added in the registry during CamelContext initialization. In this case, myDataSource is the value used with the SQL and JDBC components. 

Now, you know how to use the jdbc: and sql: component with Apache Camel.

Database Apache Camel PostgreSQL

Opinions expressed by DZone contributors are their own.

Related

  • Generate Random Test Data in PostgreSQL
  • Database Connection Pooling at Scale: PgBouncer + Multi-Tenant Postgres (10K Concurrent Connections)
  • Why PostgreSQL Vacuum Matters More Than You Think
  • No More ETL: How Lakebase Combines OLTP, Analytics in One Platform

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook