This topic describes how to use the Spring JDBC framework, MySQL Connector/J, and OceanBase Cloud to build an application for basic database operations, such as table creation, data insertion, and data query.
Download the spring-jdbc-mysql-client sample project Prerequisites
You have registered an OceanBase Cloud account, and created a cluster instance and a MySQL-compatible tenant in OceanBase Cloud. For more information, see Create a cluster instance and Create a tenant.
You have obtained the connection string of the MySQL-compatible tenant. For more information, see Obtain the connection string.
You have installed Java Development Kit (JDK) 1.8 and Maven.
You have installed Eclipse.
Note
This topic uses Eclipse IDE for Java Developers 2022-03 to run the sample code. You can also choose a suitable tool as needed.
Note
To ensure your experience with OceanBase Cloud, we recommend that you use MySQL Connector/J of the following versions:
- For MySQL Connector/J 5.x, versions 5.1.40 to 5.1.49 are recommended.
- For MySQL Connector/J 8.x, versions 8.0.7 to 8.0.25 and versions 8.2.0 to 8.4.0 are recommended.
Procedure
Note
The following procedure uses Eclipse IDE for Java Developers 2022-03 to compile and run this project in Windows. If you use another operating system or compiler, the procedure can be slightly different.
- Import the
spring-jdbc-mysql-clientproject to Eclipse - Obtain the URL of OceanBase Cloud.
- Modify the database connection information in the
spring-jdbc-mysql-clientproject. - Run the
spring-jdbc-mysql-clientproject.
Step 1: Import the spring-jdbc-mysql-client project to Eclipse
Start Eclipse and choose File > Open Projects from File System.
In the dialog box that appears, click Directory, navigate to the directory where the project is located, and click Finish to import the project.
Note
When you use Eclipse to import a Maven project, Eclipse automatically detects the
pom.xmlfile in the project, downloads the required dependency libraries based on the dependencies described in the file, and adds them to the project.
View the project.

Step 2: Obtain the URL of OceanBase Cloud
Enter the URL of OceanBase Cloud based on the obtained connection string mentioned in the "Prerequisites" section.
jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$password&useSSL=false
The parameters are described as follows:
$host: the access address of OceanBase Cloud.$port: the access port of OceanBase Cloud.$database_name: the name of the database to be accessed.Notice
The user for connecting to a tenant must have the
CREATE,INSERT,UPDATE,DELETE、SELECT, andDROPprivileges on the database.$user_name: the username of the database account.$password: the password of the tenant connection account.
For more information about the connection attributes of MySQL Connector/J, see Configuration Properties.
Here is an example:
jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?user=test_user001@mysql001&password=******&useSSL=false
Step 3: Modify the database connection information in the spring-jdbc-mysql-client project
Modify the database connection information in the Main.java file in the spring-jdbc-mysql-client/src/main/java/com/example/ directory based on the information obtained in Step 2.

The sample code is as follows:
...
String url = "jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?useSSL=false";
String username = "test_user001@mysql001";
String password = "******";
...
Step 4: Run the spring-jdbc-mysql-client project
In the project navigation view, find and expand the src/main/java directory.
Right-click the Main.java file and choose Run As > Java Application.

In the Console window of Eclipse, view the output results.

Project code
Click here to download the project code, which is a package named spring-jdbc-mysql-client.zip.
Decompress the package to obtain a folder named spring-jdbc-mysql-client. The directory structure is as follows:
spring-jdbc-mysql-client
├── src
│ └── main
│ └── java
│ └── com
│ └── example
│ └── Main.java
└── pom.xml
The files and directories are described as follows:
src: the root directory that stores the source code.main: a directory that stores the main code, including the major logic of the application.java: a directory that stores the Java source code.com: a directory that stores the Java package.example: a directory that stores the packages of the sample project.Main.java: the main class that contains logic such as the table creation and data insertion logic.pom.xml: the configuration file of the Maven project, which is used to manage project dependencies and build settings.
Code in pom.xml
pom.xml is the configuration file of the Maven project, which defines the dependencies, plug-ins, and build rules of the project. Maven is a Java project management tool that can automatically download dependencies and compile and package projects.
Perform the following steps to configure the pom.xml file:
Declare the file.
Declare the file to be an XML file that uses XML standard 1.0 and the character encoding UTF-8.
The sample code is as follows:
<?xml version="1.0" encoding="UTF-8"?>Configure namespaces and the POM model version.
xmlns: the default XML namespace for the POM, which is set tohttp://maven.apache.org/POM/4.0.0.xmlns:xsi: the XML namespace for XML elements prefixed withxsi, which is set tohttp://www.w3.org/2001/XMLSchema-instance.xsi:schemaLocation: the location of an XML schema definition (XSD) file. The value consists of two parts: the default XML namespace(http://maven.apache.org/POM/4.0.0)and the URI of the XSD file (http://maven.apache.org/xsd/maven-4.0.0.xsd).<modelVersion>: the POM model version used by the POM file, which is set to 4.0.0.
The sample code is as follows:
<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> <!-- Other configurations --> </project>Configure basic information.
<groupId>: the ID of the group to which the project belongs, which is set tocom.example.<artifactId>: the name of the project, which is set tospring-jdbc-mysql-client.<version>: the project version, which is set to1.0-SNAPSHOT.
The sample code is as follows:
<groupId>com.example</groupId> <artifactId>spring-jdbc-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>Configure the attributes of the project source file.
Specify
maven-compiler-pluginas the compiler plug-in of Maven, and set the source code version and target code version of the compiler to Java 8. This means that the project source code is compiled by using Java 8 and the compiled bytecode is compatible with the Java 8 runtime environment. This ensures that Java 8 syntax and characteristics can be correctly processed during the compilation and running of the project.Note
Java 1.8 and Java 8 are different names for the same version.
The sample code is as follows:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build>Configure the components on which the project depends.
Add the
mysql-connector-javadependency library for interactions with the database, and configure the following parameters:Note
The following code defines that the project depends on MySQL Connector/J V5.1.40. For more information about other versions, see MySQL Connector/J.
<groupId>: the ID of the group to which the dependency belongs, which is set tomysql.<artifactId>: the name of the dependency, which is set tomysql-connector-java.<version>: the version of the dependency, which is set to5.1.40.
The sample code is as follows:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>Add the
spring-jdbcdependency library and configure the following parameters:<groupId>: the ID of the group to which the dependency belongs, which is set toorg.springframework.<artifactId>: the name of the dependency, which is set tospring-jdbc.<version>: the version of the dependency, which is set to5.2.0.RELEASE.
The sample code is as follows:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.0.RELEASE</version> </dependency>
Code in Main.java
The Main.java file is a part of the sample application. Code in this file demonstrates how to perform database operations by using the Spring JDBC framework. The code first configures the database connection information, and then creates a JdbcTemplate object to perform database operations. It also provides examples of creating tables, inserting data, and querying data.
Perform the following steps to configure the Main.java file:
Define the package and import required classes.
- Declare the name of the package to which the current code belongs as
com.example. - Import the
JdbcTemplateclass, which is the core class in the Spring JDBC framework and is used to perform database operations. - Import the
DriverManagerDataSourceclass, which is a data source class provided by Spring that implements theDataSourceinterface and is used to configure database connection information.
The sample code is as follows:
package com.example; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource;- Declare the name of the package to which the current code belongs as
Create a
Mainclass and define amainmethod.- Define a public class named
Mainas the entry to the application. The class name must be the same as the file name. - Define a public static method named
main, which is used as the execution start point of the application. - Define other database operations.
The sample code is as follows:
public class Main { public static void main(String[] args) { // Database connection information // Create a data source. // Create a JdbcTemplate object. // Create a table. // Insert data. // Update data. // Delete data. // Query data. // Drop the table. } }- Define a public class named
Define the database connection information.
Define the URL, username, and password for connecting to the database. You must replace
$host,$port,$database_name,$user_name, and$passwordwith the actual database connection information.The sample code is as follows:
String url = "jdbc:mysql://$host:$port/$database_name?useSSL=false"; String username = "$user_name"; String password = "$password";Create a data source.
Create a
DriverManagerDataSourceobject and configure the database connection information, including the driver class name, database URL, username, and password. Perform the following steps:- Create a
DriverManagerDataSourceobject that configures the database connection information. - Set the class name of the database driver. Call the
setDriverClassNamemethod to set the name of the database driver class tocom.mysql.jdbc.Driver. - Specify the URL for connecting to the database. Call the
setUrlmethod to set the database URL. - Set the username. Call the
setUsernamemethod to set the database username. - Set the password. Call the
setPasswordmethod to set the database password.
The sample code is as follows:
DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password);- Create a
Create the
JdbcTemplateobject.JdbcTemplateis one of the core classes of the Spring JDBC framework.JdbcTemplateprovides methods to perform database operations, such as executing SQL statements, updating data, and querying data.The sample code is as follows:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);Create a table.
- Define an SQL statement that creates a table. In the SQL statement, set the table name to
test_springjdbcand define two columns:idof theINTtype andnameof theVARCHAR(20)type. - Execute the SQL statement to create the table. The
jdbcTemplateobject executes the statement by calling theexecutemethod. - Print a success message to the console.
The sample code is as follows:
String createTableSql = "CREATE TABLE test_springjdbc (id INT, name VARCHAR(20))"; jdbcTemplate.execute(createTableSql); System.out.println("Create table successfully.");- Define an SQL statement that creates a table. In the SQL statement, set the table name to
Insert data.
- Define an SQL statement that inserts data. In the SQL statement, set the target table to
test_springjdbcand the target columns toidandname, and insert(1,'A1'),(2,'A2'), and(3,'A3'). - Execute the SQL statement to insert data. The
jdbcTemplateobject executes the statement by calling theupdatemethod. - Print a success message to the console.
The sample code is as follows:
String insertDataSql = "INSERT INTO test_springjdbc (id,name) VALUES (1,'A1'), (2,'A2'), (3,'A3')"; jdbcTemplate.update(insertDataSql); System.out.println("Insert data successfully.");- Define an SQL statement that inserts data. In the SQL statement, set the target table to
Update data.
- Define an SQL statement that updates the
namefield toA11for the row whereidis1in the table namedtest_springjdbc. - Execute the SQL statement. The
jdbcTemplateobject executes the statement by calling theupdatemethod. - Print a success message to the console.
The sample code is as follows:
String updateDataSql = "UPDATE test_springjdbc SET name = 'A11' WHERE id = 1"; jdbcTemplate.update(updateDataSql); System.out.println("Update data successfully.");- Define an SQL statement that updates the
Delete data.
- Define an SQL statement that deletes the row where
idis2from thetest_springjdbctable. - Execute the SQL statement. The
jdbcTemplateobject executes the statement by calling theupdatemethod. - Print a success message to the console.
The sample code is as follows:
String deleteDataSql = "DELETE FROM test_springjdbc WHERE id = 2"; jdbcTemplate.update(deleteDataSql); System.out.println("Delete data successfully.");- Define an SQL statement that deletes the row where
Query data.
- Define an SQL statement that queries data. In the SQL statement, use
SELECT *to select all columns and specify to query data from thetest_springjdbctable. - Execute the SQL statement to query data. The
jdbcTemplateobject executes the statement by calling thequerymethod and accepts a callback function as a parameter. - Code in the callback function uses a
ResultSetobject (rs) to obtain and process each row in the query result. The callback function uses thegetIntandgetStringmethods to get the values of theidandnamecolumns from theResultSetobject and prints them to the console. Finally, the callback function returnsnull. - Print a success message to the console.
The sample code is as follows:
String selectDataSql = "SELECT * FROM test_springjdbc"; jdbcTemplate.query(selectDataSql, (rs, rowNum) -> { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("id: " + id + ", name: " + name); return null; }); System.out.println("Query data successfully.");- Define an SQL statement that queries data. In the SQL statement, use
Drop the table.
- Define an SQL statement that drops the
test_springjdbctable from the database. - Execute the SQL statement. The
jdbcTemplateobject executes the statement by calling theexecutemethod. - Print a success message to the console.
The sample code is as follows:
String deleteTableSql = "DROP TABLE test_springjdbc"; jdbcTemplate.execute(deleteTableSql); System.out.println("Table drop successfully.");- Define an SQL statement that drops the
Complete code
<?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.example</groupId>
<artifactId>spring-jdbc-mysql-client</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
</dependencies>
</project>
package com.example;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class Main {
public static void main(String[] args) {
// Specify the database connection information.
String url = "jdbc:mysql://$host:$port/$database_name?useSSL=false";
String username = "$user_name";
String password = "$password";
// Create a data source.
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
// Create a JdbcTemplate object.
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
// Create a table.
String createTableSql = "CREATE TABLE test_springjdbc (id INT, name VARCHAR(20))";
jdbcTemplate.execute(createTableSql);
System.out.println("Create table successfully.");
// Insert data.
String insertDataSql = "INSERT INTO test_springjdbc (id,name) VALUES (1,'A1'), (2,'A2'), (3,'A3')";
jdbcTemplate.update(insertDataSql);
System.out.println("Insert data successfully.");
// Update data.
String updateDataSql = "UPDATE test_springjdbc SET name = 'A11' WHERE id = 1";
jdbcTemplate.update(updateDataSql);
System.out.println("Update data successfully.");
// Delete data.
String deleteDataSql = "DELETE FROM test_springjdbc WHERE id = 2";
jdbcTemplate.update(deleteDataSql);
System.out.println("Delete data successfully.");
// Query data.
String selectDataSql = "SELECT * FROM test_springjdbc";
jdbcTemplate.query(selectDataSql, (rs, rowNum) -> {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id: " + id + ", name: " + name);
return null;
});
System.out.println("Query data successfully.");
// Drop the table.
String deleteTableSql = "DROP TABLE test_springjdbc";
jdbcTemplate.execute(deleteTableSql);
System.out.println("Table drop successfully.");
}
}
References
For more information about MySQL Connector/J, see Overview of MySQL Connector/J.