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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Comparing Managed Postgres Options on The Azure Marketplace
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Database Query Service With OpenAI and PostgreSQL in .NET
  • PostgreSQL 12 End of Life: What to Know and How to Prepare

Trending

  • Event Driven Architecture (EDA) - Optimizer or Complicator
  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • Rust, WASM, and Edge: Next-Level Performance
  • Enforcing Architecture With ArchUnit in Java
  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
DZone Core CORE ·
Dec. 26, 17 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
29.7K 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

  • Comparing Managed Postgres Options on The Azure Marketplace
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Database Query Service With OpenAI and PostgreSQL in .NET
  • PostgreSQL 12 End of Life: What to Know and How to Prepare

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!