This topic describes how to use the Spring JDBC framework, MySQL Connector/J, and OceanBase Database to build an application that performs basic database operations, such as creating a table, inserting data, and querying data.
Prerequisites
You have installed OceanBase Database and created a MySQL tenant.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
Note
The code examples in this topic are running in Eclipse IDE for Java Developers 2022-03. You can also use other tools of your choice to run the code examples.
Procedure
Note
The steps in this topic are for compiling and running the project in the Windows environment by using Eclipse IDE for Java Developers 2022-03. If you are using a different operating system or compiler, the steps may vary slightly.
- Import the
spring-jdbc-mysql-clientproject into Eclipse. - Obtain the URL of OceanBase Database.
- 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 into Eclipse
Start Eclipse and choose File > Open Projects from File System from the menu bar.
In the dialog box that appears, click Directory to select the project directory and then click Finish.
Note
When you import a Maven project into Eclipse, it automatically detects the
pom.xmlfile in the project, downloads the required dependency libraries based on the described dependencies in the file, and adds them to the project.
View the project.

Step 2: Obtain the URL of OceanBase Database
Contact the deployment personnel or administrator of OceanBase Database to obtain the database connection string.
Here is an example:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -DtestFor more information about the connection string, see Connect to an OceanBase tenant by using OBClient.
Fill in the corresponding information in the URL based on the OceanBase Database connection string.
jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$password&useSSL=falseParameter description:
$host: the IP address for connecting to OceanBase Database. If you connect to OceanBase Database through OceanBase Database Proxy (ODP), use the IP address of an ODP. If you connect to OceanBase Database directly, use the IP address of an OBServer node.$port: the port for connecting to OceanBase Database. If you connect to OceanBase Database through ODP, the default port is2883, which can be customized when ODP is deployed. If you connect to OceanBase Database directly, the default port is2881, which can be customized when OceanBase Database is deployed.$database_name: the name of the database to be accessed.Notice
The user for connecting to the tenant must have the
CREATE,INSERT,UPDATE,DELETE,SELECT, andDROPprivileges on the database. For more information about user privileges, see Privilege types in MySQL mode.$user_name: the tenant connection account. The common format for connecting to OceanBase Database through ODP isusername@tenant name#cluster nameorcluster name:tenant name:username. The format for connecting to OceanBase Database directly isusername@tenant name.$password: the account password.
For more information about the connection properties of MySQL Connector/J, see Configuration Properties.
Here is an example:
jdbc:mysql://xxx.xxx.xxx.xxx:2881/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 spring-jdbc-mysql-client/src/main/java/com/example/Main.java file based on the information obtained in Step 2: Obtain the URL of OceanBase Database.

Here is an example:
- The IP address of an OBServer node is
xxx.xxx.xxx.xxx. - The access port is 2881.
- The name of the database to be accessed is
test. - The tenant connection account is
test_user001@mysql001.mysql001is a MySQL tenant created in OceanBase Database, andtest_user001is the username of themysql001tenant. - The password is
******.
Sample code:
String url = "jdbc:mysql://xxx.xxx.xxx.xxx:2881/test?useSSL=false";
String username = "test_user001@mysql001";
String password = "******";
Step 4: Run the spring-jdbc-mysql-client project
In the Project Explorer view, find and expand the src/main/java directory.
Right-click the Main.java file and choose Run As > Java Application.

View the output in the console window of Eclipse.

Project code introduction
Click spring-jdbc-mysql-client to download the project code, which is a compressed file named spring-jdbc-mysql-client.zip.
After decompressing it, you will find 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
File description:
src: the root directory for source code.main: the main code directory, containing the core logic of the application.java: the directory for Java source code.com: the directory for Java package.example: the directory for the package of the sample project.Main.java: the main class, containing logic for creating tables and inserting data.pom.xml: the configuration file for the Maven project, used to manage project dependencies and build settings.
pom.xml code introduction
The pom.xml file is the configuration file for a Maven project, defining the project's dependencies, plugins, and build rules. Maven is a Java project management tool that can automatically download dependencies, compile, and package projects.
The pom.xml file in this topic includes the following main sections:
File declaration statement.
This statement declares the file as an XML file using XML version
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure the POM namespace and POM model version.
- Use
xmlnsto specify the POM namespace ashttp://maven.apache.org/POM/4.0.0. - Use
xmlns:xsito specify the XML namespace ashttp://www.w3.org/2001/XMLSchema-instance. - Use
xsi:schemaLocationto specify the POM namespace ashttp://maven.apache.org/POM/4.0.0and the location of the POM XSD file ashttp://maven.apache.org/xsd/maven-4.0.0.xsd. - Use the
<modelVersion>element to specify the POM model version used by the POM file as4.0.0.
Sample code:
<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>- Use
Configure basic information.
- Use
<groupId>to specify the project's organization ascom.example. - Use
<artifactId>to specify the project's name asspring-jdbc-mysql-client. - Use
<version>to specify the project's version as1.0-SNAPSHOT.
Sample code:
<groupId>com.example</groupId> <artifactId>spring-jdbc-mysql-client</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the properties of the project's source files.
Specify the Maven compiler plugin as
maven-compiler-pluginand set both the source code and target Java versions to 8. This means the project's source code is written using Java 8 features, and the compiled bytecode will also be compatible with the Java 8 runtime environment. This setup ensures that the project can correctly handle Java 8 syntax and features during compilation and runtime.Note
Java 1.8 and Java 8 are different names for the same version.
Sample code:
<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 that the project depends on.
Add the
mysql-connector-javadependency library for interacting with the database:Note
This section of code defines the project's dependency on MySQL Connector/J version 5.1.40. For information about other versions, see MySQL Connector/J.
- Use
<groupId>to specify the dependency's organization asmysql. - Use
<artifactId>to specify the dependency's name asmysql-connector-java. - Use
<version>to specify the dependency's version as5.1.40.
Sample code:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>- Use
Add the
spring-jdbcdependency library:- Use
<groupId>to specify the dependency's organization asorg.springframework. - Use
<artifactId>to specify the dependency's name asspring-jdbc. - Use
<version>to specify the dependency's version as5.2.0.RELEASE.
Sample code:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.0.RELEASE</version> </dependency>- Use
Main.java code introduction
The Main.java file is part of the sample program and demonstrates how to use the Spring JDBC framework to perform database operations. It first configures the database connection information and then creates a JdbcTemplate object to execute database operations. The code also includes examples of creating tables, inserting data, and querying data.
The code in the Main.java file in this topic mainly includes the following parts:
Define the package and import the necessary classes.
- Declare the package name of the current code as
com.example. - Import the
JdbcTemplateclass, which is a core class in the Spring JDBC framework used to execute 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.
Code:
package com.example; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource;- Declare the package name of the current code as
Create a
Mainclass and define themainmethod.- Define a public class named
Mainas the entry point of the program. The class name must match the file name. - Define a public static method
mainas the starting point of the program. - Other database operations.
Code:
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 // Delete the table } }- Define a public class named
Define the database connection information.
Define the URL, username, and password for connecting to the database. You need to replace
$host,$port,$database_name,$user_name, and$passwordwith the actual database connection information.Code:
String url = "jdbc:mysql://$host:$port/$database_name?useSSL=false"; String username = "$user_name"; String password = "$password";Parameter description:
$host: the IP address for connecting to OceanBase Database. For ODP connection, use an ODP address. For direct connection, use the IP address of an OBServer node.$port: the port for connecting to OceanBase Database. For ODP connection, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase Database is deployed.$database_name: the name of the database to be accessed.$user_name: specified by the-uparameter. The format is user@tenant#cluster name or username@SERVICE:service name. When the format user@tenant#cluster name is used, the default tenant issysand the administrator user isroot. When directly connecting to the database, the cluster name can be omitted. When using ODP connection, the cluster name must be specified.$password: the password for the account.
Create a data source.
Create a
DriverManagerDataSourceobject and configure the database connection information, including the driver class name, database URL, username, and password. The specific steps are as follows:- Create a
DriverManagerDataSourceobject to configure the database connection information. - Set the driver class name: call the
setDriverClassNamemethod and set the database driver class name tocom.mysql.jdbc.Driver. - Set the database URL: call the
setUrlmethod and set the database URL. - Set the username: call the
setUsernamemethod and set the database username. - Set the password: call the
setPasswordmethod and set the database password.
Code:
DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password);- Create a
Create a
JdbcTemplateobject.Create a
JdbcTemplateobject, which is one of the core classes in the Spring JDBC framework. TheJdbcTemplateclass provides methods for executing database operations, such as executing SQL statements, updating data, and querying data.Code:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);Create a table.
- Define an SQL statement for creating a table. The SQL statement specifies the table name as
test_springjdbcand defines two columns: one is anINTcolumn namedid, and the other is aVARCHAR(20)column namedname. - Execute the SQL statement for creating the table. The
jdbcTemplateobject calls theexecutemethod to execute the SQL statement for creating the table. - Output a message indicating that the table was successfully created.
Code:
String createTableSql = "CREATE TABLE test_springjdbc (id INT, name VARCHAR(20))"; jdbcTemplate.execute(createTableSql); System.out.println("Create table successfully.");- Define an SQL statement for creating a table. The SQL statement specifies the table name as
Insert data.
- Define an SQL statement for inserting data. The SQL statement specifies the table to be inserted into as
test_springjdbc, with columnsidandname. Two rows of data are inserted:(1,'A1'),(2,'A2'), and(3,'A3'). - Execute the SQL statement for inserting data. The
jdbcTemplateobject calls theupdatemethod to execute the SQL statement for inserting data. - Output a message indicating that the data was successfully inserted.
Code:
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 for inserting data. The SQL statement specifies the table to be inserted into as
Update data.
- Define an SQL statement for updating the
namefield of the record withidequal to1in thetest_springjdbctable toA11. - Execute the SQL statement using the
jdbcTemplateobject to apply the update operation to the database. - Output a message indicating that the data was successfully updated.
Code:
String updateDataSql = "UPDATE test_springjdbc SET name = 'A11' WHERE id = 1"; jdbcTemplate.update(updateDataSql); System.out.println("Update data successfully.");- Define an SQL statement for updating the
Delete data.
- Define an SQL statement for deleting the record with
idequal to2from thetest_springjdbctable. - Execute the SQL statement using the
jdbcTemplateobject to apply the delete operation to the database. - Output a message indicating that the data was successfully deleted.
Code:
String deleteDataSql = "DELETE FROM test_springjdbc WHERE id = 2"; jdbcTemplate.update(deleteDataSql); System.out.println("Delete data successfully.");- Define an SQL statement for deleting the record with
Query data.
- Define an SQL statement for querying data. The SQL statement uses
SELECT *to select all columns from thetest_springjdbctable. - Execute the SQL statement for querying data. The
jdbcTemplateobject calls thequerymethod to execute the SQL statement for querying data and receives a callback function as a parameter. - The code in the callback function uses the
ResultSetobject (rs) to obtain each row of data from the query results and process it. The callback function uses thegetIntandgetStringmethods of theResultSetobject to obtain the values of theidandnamecolumns and prints them to the console. Finally, the callback function returnsnull. - Output a message indicating that the data was successfully queried.
Code:
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 for querying data. The SQL statement uses
Drop the table.
- Define an SQL statement to drop the
test_springjdbctable from the database. - Execute the SQL statement using the
jdbcTemplateobject to apply the drop table operation to the database. - Output a message indicating that the table was successfully dropped.
Here is the code:
String deleteTableSql = "DROP TABLE test_springjdbc"; jdbcTemplate.execute(deleteTableSql); System.out.println("Table drop successfully.");- Define an SQL statement to drop 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) {
// Database Connect Information
String url = "jdbc:mysql://$host:$port/$database_name?useSSL=false";
String username = "$user_name";
String password = "$password";
// create 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 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.");
// Delete table
String deleteTableSql = "DROP TABLE test_springjdbc";
jdbcTemplate.execute(deleteTableSql);
System.out.println("Table drop successfully.");
}
}
Related documentation
For more information about MySQL Connector/J, see Overview of MySQL Connector/J. MySQL Mode|

Download the spring-jdbc-mysql-client sample project
Connect to OceanBase Database by using Spring JDBC (MySQL mode)