This topic introduces how to build an application by using the Spring Data JDBC framework, OceanBase Connector/J, and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, data updating, data query, and data deletion.
Prerequisites
You have installed OceanBase Database and created an Oracle tenant.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
Note
The tool used to run the sample code in this topic is Eclipse IDE for Java Developers (2022-03), but you can also choose a tool that suits your personal preference to run the code.
Procedure
Note
The steps outlined in this topic are for the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.
- Import the
spring-jdbc-oceanbase-clientproject into Eclipse. - Obtain the URL of OceanBase Database.
- Modify the database connection information in the
spring-jdbc-oceanbase-clientproject. - Run the
spring-jdbc-oceanbase-clientproject.
Step 1: Import the spring-jdbc-oceanbase-client project into Eclipse
Start Eclipse and choose File > Open Projects from File System.
In the dialog box that appears, click Directory to browse and select the project, and then click Finish.
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 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@oracel001 -p******For more information about connection strings, see Connect to an OceanBase tenant by using OBClient.
Fill in the URL below based on the OceanBase Database connection string.
jdbc:oceanbase://$host:$port/$schema_name?user=$user_name&password=$passwordwhere
$hostspecifies the IP address for connecting to OceanBase Database. For connection through OceanBase Database Proxy (ODP), this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.$portspecifies the port for connecting to OceanBase Database. For connection through ODP, 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.$schema_namespecifies the name of the schema to be accessed.Notice
The user used to connect to a tenant must have the
CREATE SESSIONprivilege and theCREATE TABLE,DROP TABLE,INSERT,DELETE,UPDATE, andSELECTprivileges on the schema. For more information about the privileges, see Privilege types in Oracle mode.$user_namespecifies the tenant account. For connection through ODP, the tenant account can be in theusername@tenant name#cluster nameorcluster name:tenant name:usernameformat. For direct connection, the tenant account is in theusername@tenant nameformat.$passwordspecifies the password of the account.
For more information about the URL parameters of OceanBase Connector/J, see Database URL.
Here is an example:
jdbc:oceanbase://xxx.xxx.xxx.xxx:2881/test_schema001?user=test_user001@oracel001&password=******
Step 3: Modify the database connection information in the spring-jdbc-oceanbase-client project
Modify the database connection information in the spring-jdbc-oceanbase-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 the OBServer node is
xxx.xxx.xxx.xxx. - The port is
2881. - The name of the schema to be accessed is
test_schema001. - The tenant account is
test_user001@oracle001, whereoracle001is a user tenant created in the Oracle mode of OceanBase Database, andtest_user001is a username in theoracle001tenant. - The password is
******.
The sample code is as follows:
...
String url = "jdbc:oceanbase://xxx.xxx.xxx.xxx:2881/test_schema001";
String username = "test_user001@oracle001";
String password = "******";
...
Step 4: Run the spring-jdbc-oceanbase-client project
In the Project Explorer view, locate and expand the src/main/java folder.
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-oceanbase-client to download the project code, which is a compressed file named spring-jdbc-oceanbase-client.zip.
After decompressing it, you will find a folder named spring-jdbc-oceanbase-client. The directory structure is as follows:
spring-jdbc-oceanbase-client
├── src
│ └── main
│ └── java
│ └── com
│ └── example
│ └── Main.java
└── pom.xml
Here is a breakdown of the files and directories:
src: the root directory for storing the source code.main: the directory for storing the main code, including the major logic of the application.java: the directory for storing the Java source code.com: the directory for storing the Java package.example: the directory for storing the packages of the sample project.Main.java: the main class that contains logic such as table creation and data insertion.pom.xml: the configuration file of the Maven project, which is used to manage project dependencies and build settings.
Code in pom.xml
The pom.xml file is a configuration file for Maven projects, which defines the dependencies, plug-ins, and build rules of the projects. Maven is a Java project management tool that can automatically download dependencies, compile, and package the projects.
To configure the pom.xml file, perform the following steps:
Declare the file.
Declare the file to be an XML file that uses XML standard
1.0and character encodingUTF-8.The sample code is as follows:
<?xml version="1.0" encoding="UTF-8"?>Configure the namespaces and the POM model version.
- Use
xmlnsto specifyhttp://maven.apache.org/POM/4.0.0as the default XML namespace for the POM. - Use
xmlns:xsito specifyhttp://www.w3.org/2001/XMLSchema-instanceas the XML namespace for xsi-prefixed elements. - Use
xsi:schemaLocationto provide a mapping from the default XML namespace for the POM (http://maven.apache.org/POM/4.0.0) to the location of the POM’s XML schema definition (XSD) file (http://maven.apache.org/xsd/maven-4.0.0.xsd). - Use
<modelVersion>to specify4.0.0as the model version used by the POM.
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>- Use
Configure basic project information.
- Use
<groupId>to specifycom.exampleas the ID of the project group. - Use
<artifactId>to specifyspring-jdbc-oceanbase-clientas the ID of the project. - Use
<version>to specify1.0-SNAPSHOTas the project version.
The sample code is as follows:
<groupId>com.example</groupId> <artifactId>spring-jdbc-oceanbase-client</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the properties of the project’s source file.
Specify the Maven compiler plug-in as
maven-compiler-plugin, and set both the source code and target Java versions to 8. This means that the project’s source code is written using Java 8, and the compiled bytecode will also be compatible with the Java 8 runtime environment. This setup ensures that the project can correctly handle the syntax and features of Java 8 during compilation and runtime.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 project dependencies.
Add the
oceanbase-clientdependency to interact with the database.- Use
<groupId>to specifycom.oceanbaseas the ID of the group that the dependency belongs to. - Use
<artifactId>to specifyoceanbase-clientas the dependency ID. - Use
<version>to specify2.4.2as the dependency version.
Note
The following code defines that the project depends on OceanBase Connector/J V2.4.2. For more information about other versions, see OceanBase Connector/J.
The sample code is as follows:
<dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency>- Use
Add the
spring-jdbcdependency.- Use
<groupId>to specifyorg.springframeworkas the ID of the group that the dependency belongs to. - Use
<artifactId>to specifyspring-jdbcas the dependency ID. - Use
<version>to specify5.2.0.RELEASEas the dependency version.
The sample code is as follows:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.0.RELEASE</version> </dependency>- Use
Code in Main.java
The Main.java file is a part of the sample program. Code in this file demonstrates how to perform database operations by using the Spring Data 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.
To configure the Main.java file, perform the following steps:
Define the package and import necessary classes.
- Declare the name of the parent package of the current code to be
com.example. - Import the
JdbcTemplateclass, which is the core class in the Spring Data JDBC framework for performing database operations. - Import the
DriverManagerDataSourceclass, which is aDataSourceimplementation provided by Spring for configuring 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 parent package of the current code to be
Define the
Mainclass and themainmethod.- Define a public class named
Mainas the entry to the program. The class name must be the same as the file name. - Define a public static method
mainas the execution start point for the program. - 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 a table. } }- Define a public class named
Define the database connection information.
Define the URL, username, and password for connecting to the database. Replace
$host,$port,$schema_name,$user_name, and$passwordwith actual database connection information.The sample code is as follows:
String url = "jdbc:oceanbase://$host:$port/$schema_name"; String username = "$user_name"; String password = "$password";where
$hostspecifies the IP address for connecting to OceanBase Database. For connection through ODP, this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.$portspecifies the port for connecting to OceanBase Database. For connection through ODP, 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.$schema_namespecifies the name of the database to access.For more information about URL parameters, see Database URL.
$user_namespecifies the tenant account. For connection through ODP, the tenant account can be in theusername@tenant name#cluster nameorcluster name:tenant name:usernameformat. For direct connection, the tenant account is in theusername@tenant nameformat.$passwordspecifies the account password.
Create a data source.
Create a
DriverManagerDataSourceobject and configure the database connection information, including the driver class name, database URL, username, and password. The steps are as follows:- Create a
DriverManagerDataSourceobject for configuring the database connection information. - Call the
setDriverClassNamemethod to set the name of the database driver class tocom.oceanbase.jdbc.Driver. This driver class is used to connect to OceanBase Database. - Set the database URL by calling the
setUrlmethod. - Set the database username by calling the
setUsernamemethod. - Set the database password by calling the
setPasswordmethod.
The sample code is as follows:
DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.oceanbase.jdbc.Driver"); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password);- Create a
Create a
JdbcTemplateobject.The
JdbcTemplateobject is one of the core classes of the Spring Data 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 theNUMBERtype andnameof theVARCHAR(20)type. - Execute the SQL statement to create a 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 NUMBER, name VARCHAR2(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(1,'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'), (1,'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 the tabletest_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 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 a 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 examples
<?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-oceanbase-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>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.2</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:oceanbase://$host:$port/$schema_name";
String username = "$user_name";
String password = "$password";
// create data source
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.oceanbase.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 NUMBER, name VARCHAR2(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'), (1,'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.");
}
}
References
For more information about OceanBase Connector/J, see OceanBase Connector/J.
Download the spring-jdbc-oceanbase-client sample project