How to use Camel JPA with Spring Boot

In this tutorial, we’ll learn how to use the Camel JPA component to read and write data from a PostgreSQL database. Specifically, we’ll cover how to create a Camel route that reads data from a JSON file, maps it to a JPA entity, and then inserts it into a PostgreSQL database using the Camel JPA component. We’ll wrap it all into a Spring Boot application.

Pre-Requisites

Before starting, you will need to have the following:

  • Basic knowledge of Java and Spring Boot
  • Maven installed and set up
  • An IDE (Integrated Development Environment) like Eclipse or IntelliJ IDEA installed

Project Setup

First, let’s create a new Spring Boot project using Maven. For this purpose you can use Spring Boot application initializer:

spring boot camel JPA example

You can include as initial dependencies Spring Data JPA and PostgreSQL Driver.

Click on generate to continue. Unzip the project in a folder of your Drive and import it with your IDE.

Next, we will include the Camel Spring Boot starter we need for our application:

<dependency>
         <groupId>org.apache.camel.springboot</groupId>
         <artifactId>camel-spring-boot-starter</artifactId>
</dependency>

<dependency>
         <groupId>org.apache.camel.springboot</groupId>
         <artifactId>camel-jpa-starter</artifactId>
</dependency>

<dependency>
         <groupId>org.apache.camel.springboot</groupId>
         <artifactId>camel-jackson-starter</artifactId>
</dependency>

Finally, please note that, to avoid setting the version for the above starters we recommend including the camel-spring-boot-dependencies pom file in your dependencyManagement section_

 <dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-spring-boot-dependencies</artifactId>
    <version>${camel-version}</version>
    <type>pom</type>
    <scope>import</scope>
 </dependency>

Configuring the Database

We will be using PostgreSQL as database. For this purpose, include in the application.properties (or equivalent), the following configuration which will create a datasource for a PostgreSQL Database:

camel.springboot.main-run-controller=true

spring.datasource.url=jdbc:postgresql://localhost:5432/cameldb?createDatabaseIfNotExist=true
spring.datasource.username=camel
spring.datasource.password=camel
spring.datasource.platform=cameldb
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = create-drop

To connect to the above Database, you can start a Docker daemon with the following configuration:

docker run --ulimit memlock=-1:-1 -it --rm=true --memory-swappiness=0 --name camel_jpa -e POSTGRES_USER=camel -e POSTGRES_PASSWORD=camel -e POSTGRES_DB=cameldb -p 5432:5432 postgres:13

Creating the JPA Entity

Next, let’s create a JPA entity that maps to our database table. Create a new package com.example.model and create a new class Operation.java inside this package.

@Entity
@Table
public class Operation {

    @Id
    private Long id;
    private Double amount;
    private String currency;

    // getters and setters
}

Using the Camel JPA Component

Next, we will add a Route that will demonstrate how to use the JPA Component as Producer and as Consumer:

@Component
public class MyRouteBuilder extends RouteBuilder {

    @Override
    public void configure() throws Exception {

        from("file:src/main/resources/data?noop=true")
        .unmarshal().json(JsonLibrary.Jackson, Operation.class)
        .log("Found document: ${body}")
        .to("jpa:com.example.Operation?persistenceUnit=postgresql&flushOnSend=true");



        from("jpa:com.example.Operation?persistenceUnit=postgresql&consumeDelete=false")
        .process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                Operation operation = exchange.getIn().getBody( Operation.class );
            
                Double amount = operation.getAmount();
              
                exchange.getIn().setHeader("amount", amount);
            }
        })   .log("Amount: ${headers.amount}");
       
                          
    }
}

In this first Route, we are using the JPA Component as Producer:

  • Firstly, we are reading a JSON File from the resources/data Folder.
  • Next, we unmarshal it into the Operation Class
  • Then, we use the MessageExchange (which contains the Operation Java Class) as Producer for the JPA Component.

In the second route, we are using the JPA Component as Consumer.

  • In practice, the will execute a “SELECT * from Operation”. Please note that we are setting consumeDelete=false otherwise the JPA Component will follow up with a DELETE of the Data after Consumption.
  • Then, the consumer Entity Data will go to a Processor that will set into the Header the value of the Operation amount.

Here is the final Project view which includes also a sample JSON file (operation.json) in the resources/data folder:

camel jpa tutorial

Running the application

Finally you can run the application with mvn install spring-boot:run. From the output, you should be able to see that, the JSON Document will be inserted into the DB as Operation Entity. Then, the second Route will poll the Operation tables and print the value of “Amount” on the Console

2023-05-08 12:46:18.801  INFO 35217 --- [/resources/data] route1                                   : Found document: Operation [id=12345, amount=50.0, currency=USD]
Hibernate: select operation0_.id as id1_0_0_, operation0_.amount as amount2_0_0_, operation0_.currency as currency3_0_0_ from operation operation0_ where operation0_.id=?
Hibernate: insert into operation (amount, currency, id) values (?, ?, ?)
Hibernate: select operation0_.id as id1_0_, operation0_.amount as amount2_0_, operation0_.currency as currency3_0_ from operation operation0_
Hibernate: select id from operation where id =? for update
2023-05-08 12:46:18.851  INFO 35217 --- [ample.Operation] route2                                   : Amount: 50.0

Conclusion

In this tutorial, we have learned how to use the Camel JPA component to integrate with a PostgreSQL database. We have shown how to read data from a file, unmarshal it into a Java object, and then insert it into a database table using the JPA component. We have also demonstrated how to read data from a database table using the JPA component.

The source code for this article is available here: https://github.com/fmarchioni/masterspringboot/tree/master/camel/camel-jpa-springboot