In this tutorial we will learn how to perform some basic JDBC operations using Camel JDBC Component.

The JDBC component enables you to access databases through JDBC, where SQL queries (SELECT) and operations (INSERT, UPDATE, etc) are sent in the message body. This component uses the standard JDBC API.

In the following example, we will create a Timer component which triggers a Processor containing a simple INSERT statement:

package com.sample;

import javax.sql.DataSource;

import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.apache.camel.main.Main;

import org.apache.camel.builder.RouteBuilder;

import org.apache.commons.dbcp.BasicDataSource;

public class JDBCExample {

	private Main main;

	public static void main(String[] args) throws Exception {
		String url = "jdbc:mysql://localhost:3306/test";
		DataSource dataSource = setupDataSource(url);

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

		CamelContext context = new DefaultCamelContext(reg);
		context.addRoutes(new JDBCExample().new MyRouteBuilder());
		context.start();
		Thread.sleep(5000);
		context.stop();
	}

	class MyRouteBuilder extends RouteBuilder {

		public void configure() {

			from("timer://foo?period=1000").process(new SimpleProcessor()).to(
					"jdbc:myDataSource");

		}
	}

	private static DataSource setupDataSource(String connectURI) {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName("com.mysql.jdbc.Driver");
		ds.setUsername("user");
		ds.setPassword("password");
		ds.setUrl(connectURI);
		return ds;
	}
}

As you can see in the above code, a BasicDataSource definition is provided by the setupDataSource. This introduces a dependency to the Commons-pool and Commons dbcp packages available here.

The Connection pool connects to a MySQL Database using the credentials contained in the main method of the class.

Finally here is the SimpleProcessor implementation which merely returns a random user to be inserted into the DB:

package com.sample;

import java.util.ArrayList;
import java.util.HashMap;
 

import java.util.UUID;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class SimpleProcessor implements Processor {
	public void process(Exchange exchange) throws Exception {
		 
		exchange.getIn().setBody("INSERT into user values ('" + UUID.randomUUID().toString() + "')");
				 	 
	}
}

Here is the list of libraries I have used to compile and run the project:

  • camel-core-2.14.1.jar
  • camel-jdbc-2.14.1.jar
  • mysql-connector-java-5.1.29-bin.jar
  • commons-dbcp-1.4.jar
  • commons-pool-1.4.jar
  • slf4j-api-1.6.6.jar
  • slf4j-simple-1.6.1.jar
0
0
0
s2smodern