VOOZH about

URL: https://www.cdata.com/kb/tech/salesforce-jdbc-spring-boot.rst

⇱ How to connect to Salesforce Data from Spring Boot


How to connect to Salesforce Data from Spring Boot

πŸ‘ Jerod Johnson
Jerod Johnson
Director, Technology Evangelism
Connect to Salesforce in a Spring Boot Application using CData JDBC Salesforce Driver

Spring Boot is a framework that makes engineering Java web applications easier. It offers the ability to create standalone applications with minimal configuration. When paired with the CData JDBC driver for Salesforce, Spring Boot can work with live Salesforce data. This article shows how to configure data sources and retrieve data in your Java Spring Boot Application, using the CData JDBC Driver for Salesforce.

With built-in optimized data processing, the CData JDBC Driver offers unmatched performance for interacting with live Salesforce data. When you issue complex SQL queries to Salesforce, the driver pushes supported SQL operations, like filters and aggregations, directly to Salesforce and utilizes the embedded SQL engine to process unsupported operations client-side (often SQL functions and JOIN operations). Its built-in dynamic metadata querying allows you to work with and analyze Salesforce data using native data types.

About Salesforce Data Integration

Accessing and integrating live data from Salesforce has never been easier with CData. Customers rely on CData connectivity to:

  • Access to custom entities and fields means Salesforce users get access to all of Salesforce.
  • Create atomic and batch update operations.
  • Read, write, update, and delete their Salesforce data.
  • Leverage the latest Salesforce features and functionalities with support for SOAP API versions 30.0.
  • See improved performance based on SOQL support to push complex queries down to Salesforce servers.
  • Use SQL stored procedures to perform actions like creating, retrieving, aborting, and deleting jobs, uploading and downloading attachments and documents, and more.

Users frequently integrate Salesforce data with:

  • other ERPs, marketing automation, HCMs, and more.
  • preferred data tools like Power BI, Tableau, Looker, and more.
  • databases and data warehouses.

For more information on how CData solutions work with Salesforce, check out our Salesforce integration page.


Getting Started


Creating the Spring Boot Project in Java

In an IDE (in this tutorial, we use IntelliJ), choose a Maven project: πŸ‘ Create a new Maven project
In the generated project, go to the pom.xml file, and add the required dependencies for Spring Boot:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
	<plugin>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-maven-plugin</artifactId>
	</plugin>

	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-install-plugin</artifactId>
		<version>2.5.1</version>
		<executions>
			<execution>
				<id>id.install-file</id>
				<phase>clean</phase>
				<goals>
					<goal>install-file</goal>
				</goals>
				<configuration>
					<file>C:\Program Files\CData[product_name] ####\lib\cdata.jdbc.salesforce.jar</file>
					<groupId>org.cdata.connectors</groupId>
					<artifactId>cdata-salesforce-connector</artifactId>
					<version>23</version>
					<packaging>jar</packaging>
				</configuration>
			</execution>
		</executions>
	</plugin>
</plugins>
</build>

<dependencies>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
	<version>2.7.0</version>
</dependency>
<dependency>
	<groupId>org.cdata.connectors</groupId>
	<artifactId>cdata-salesforce-connector</artifactId>
	<version>23</version>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
</dependencies>



<distributionManagement>
<repository>
	<uniqueVersion>false</uniqueVersion>
	<id>test</id>
	<name>My Repository</name>
	<url>scp://repo/maven2</url>
	<layout>default</layout>
</repository>
</distributionManagement>

</project>

Note: The year (####) and the version number (as seen in the provided XML script) should be adjusted according to the current version of the CData JDBC driver being utilized.

Project Structure

In the java directory, create a new package. Usually the name of the package is the name of the groupId (com.example) followed by the artifactId (.MDS). πŸ‘ Create a new Package in java folder
πŸ‘ Enter the name of the Package

Mark the "java" directory as the "Sources Root" (denoted by a blue color). To do this, right-click the java directory and choose Mark Directory as -> Sources Root (As shown below). Additionally, mark the "resources" directory as the "Resources Root." πŸ‘ Mark Directory as Sources Root

Store Database Connection Properties

Create an "application.properties" file to store the database connection properties. To do this, right-click on the "resources" folder, opt for New -> File, input the file name as "application.properties," and press Enter. πŸ‘ Create a new (configuration) file
πŸ‘ Name the file as application.properties

In the application.properties file, we set the configuration properties for the Salesforce JDBC Driver, using the Class name and JDBC URL:

	spring.datasource.driver=cdata.jdbc.salesforce.SalesforceDriver
	spring.datasource.url=jdbc:salesforce:InitiateOAuth=GETANDREFRESH;MFACode=YourMFACode

Built-in Connection String Designer

For assistance in constructing the JDBC URL, use the connection string designer built into the Salesforce JDBC Driver. Either double-click the JAR file or execute the jar file from the command-line.

java -jar cdata.jdbc.salesforce.jar

There are several authentication methods available for connecting to Salesforce: OAuth, Login (or basic), and SSO. The Login method requires you to have the username, password, and security token of the user.

OAuth Authentication (default)

The default authentication mechanism (and the one preferred by Salesforce) is OAuth. To use OAuth with CData's embedded OAuth application, leave the connection properties blank. If you have configured your own custom OAuth application with Salesforce (see the Help documentation for more information), set OAuthClientId, OAuthClientSecret, and CallbackURL to the properties for you application. Set InitiateOAuth to the desired OAuth flow ("GETANDREFRESH" will have the connector manage the entire OAuth flow).

Login (or Basic) Authentication

If you do not wish do not wish to use OAuth authentication, you can use Login (or basic) authentication. Set AuthScheme to Basic, and set the User, Password, and SecurityToken properties. You can configure your security token in Salesforce.

SSO (single sign-on) Authentication

SSO (single sign-on) can be used by setting the SSOProperties, SSOLoginUrl, and SSOExchangeURL connection properties, which allow you to authenticate to an identity provider. See the "Getting Started" chapter in the Help documentation for more information.

Multi-Factor Authentication (MFA)

If your Salesforce org has MFA enforcement enabled, set MFACode to the time-based one-time passcode (TOTP) generated by your authenticator app (such as Salesforce Authenticator or Google Authenticator). MFACode applies to both OAuth and Login authentication flows.

πŸ‘ Using the built-in connection string designer to generate a JDBC URL (Salesforce is shown.)

After setting the properties in the application.properties file, we now configure them.

Data Source Configuration

First, we mark the Salesforce data source as our primary data source. Then, we create a Data Source Bean.

Create a DriverManagerDataSource.java file and create a Bean within it, as shown below. If @Bean gives an error, Spring Boot may not have loaded properly. To fix this, go to File -> Invalidate Caches and restart. Additionally, make sure that Maven has added the Spring Boot dependencies.

To create a data source bean, we use the DriverManagerDataSource Class. This class allows us to set the properties of the data source. To create this Java class, right-click on "com.example.MDS" package, and choose New -> Java Class. πŸ‘ Create a new Java class

The following code shows the bean definition of our data source. Each driver should have a bean.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import javax.sql.DataSource;

public class DriverManagerDataSource{
	@Autowired
	private static Environment env;

	@Bean(name ="Salesforce")
	@Primary
	public static DataSource SalesforceDataSource()
	{

	DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
		dataSourceBuilder.driverClassName("cdata.jdbc.salesforce.SalesforceDriver");
		dataSourceBuilder.url("jdbc:salesforce:InitiateOAuth=GETANDREFRESH;MFACode=YourMFACode");
		return dataSourceBuilder.build();
	}
	
	//@Override
	public void setEnvironment( final Environment environment) {
	env=environment;
	}
}

Next, move the Salesforce jar file to the Documents folder (see path in command below) - The idea is to have a path without any spaces for the jar file. Then, click the Maven icon (top right corner of IntelliJ) and click "Execute Maven Goal." Now, run the following command: πŸ‘ Execute Maven Goal
πŸ‘ Run Maven install command

mvn install:install-file "-Dfile=C:\Program Files\CData[product_name] ####\lib\cdata.jdbc.salesforce.jar" -DgroupId=org.cdata.connectors -DartifactId=cdata-salesforce-connector -Dversion=23 -Dpackaging=jar

Follow either of the given steps to run this command:

  1. The "-Dfile location" can be kept as the default installation path of the CData JDBC Driver. Make sure to keep the path in quotations in this case. Also, change the year and "Dversion" based on the current version of the driver being used.
  2. As mentioned earlier in the article, in case you relocate the

After pressing enter, we see the following output: πŸ‘ Successful installation of the JDBC driver

Testing the Connection

The last step is testing the connection. Create a new Java class following the format

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import java.sql.Connection;
import java.sql.SQLException;
import static com.example.demo.DriverManagerDataSources.SalesforceDataSource;


@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
	public class MDSApplication {
		//remove the comment on the line below
		public static void main (){
		SpringApplication.run(DemoApplication.class, args);
		Connection conn = SalesforceDataSource().getConnection();
		System.out.println("Catalog: "+ conn.getCatalog());
	}
}

The output generated should look like this: πŸ‘ Successful test connection

Free Trial & More Information

Download a free, 30-day trial of the CData JDBC Driver for Salesforce and start working with your live Salesforce in Spring Boot.

Ready to get started?

Download a free trial of the Salesforce Driver to get started:

 Download Now

Learn more:

πŸ‘ Salesforce Icon
Salesforce JDBC Driver

Rapidly create and deploy powerful Java applications that integrate with Salesforce account data including Leads, Contacts, Opportunities, Accounts, and more!