This topic describes how to use HikariCP, OceanBase Connector/J, and OceanBase Cloud to build an application that performs basic database operations, including creating tables, inserting, deleting, updating, and querying data.
Download the hikaricp-oceanbase-client sample project Prerequisites
You have registered an OceanBase Cloud account and created an instance and an OceanBase Cloud Oracle compatible tenant. For more information, see Create an instance and Create a tenant.
You have obtained the connection string of the target OceanBase Cloud Oracle compatible tenant. For more information, see Obtain a connection string.
You have installed JDK 1.8 and Maven.
You have installed Eclipse.
Note
The code examples in this topic are run in Eclipse IDE for Java Developers 2022-03. You can also choose a tool of your preference to run the sample code.
Procedure
Note
The following steps are for compiling and running the project in the Windows environment by using Eclipse IDE for Java Developers 2022-03. If you use other operating systems or compilers, the steps may vary.
Step 1: Import the hikaricp-oceanbase-client project into Eclipse
Start Eclipse and choose File > Open Projects from File System.
In the dialog box that appears, click Directory to select the project directory and 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: Modify the database connection information in the hikaricp-oceanbase-client project
Modify the database connection information in the hikaricp-oceanbase-client/src/main/resources/db.properties file based on the connection string information obtained in the prerequisites.
Here is an example:
...
jdbcUrl=jdbc:oceanbase://t5******.********.oceanbase.cloud:1521/test_schema001
username=test_user
password=******
...
- The connection address is
t5******.********.oceanbase.cloud. - The access port is 1521.
- The name of the database to be accessed is
test_schema001. - The tenant account is
test_user. - The password is
******.
Step 3: Run the hikaricp-oceanbase-client project
In the Project Explorer view, locate and expand the src/main/java directory.
Right-click the Main.java file and choose Run As > Java Application.

View the project logs and output in the Eclipse console window.

You can also execute the following SQL statement in OceanBase Client (OBClient) to view the result.
obclient [SYS]> SELECT * FROM test_schema001.test_hikaricp;The returned result is as follows:
+------+-------------+ | ID | NAME | +------+-------------+ | 1 | test_update | +------+-------------+ 1 row in set
Project code
Click hikaricp-oceanbase-client to download the project code, which is a compressed file named hikaricp-oceanbase-client.zip.
After decompressing the file, you will find a folder named hikaricp-oceanbase-client. The directory structure is as follows:
hikaricp-oceanbase-client
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── Main.java
│ └── resources
│ └── db.properties
└── pom.xml
File description:
src: the root directory of the 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 packages.example: the directory for packages of the sample project.Main.java: the main class file, containing logic for creating tables, inserting, deleting, updating, and querying data.resources: the directory for resource files, including configuration files.db.properties: the configuration file for the connection pool, containing relevant database connection parameters.pom.xml: the configuration file for the Maven project, used to manage project dependencies and build settings.
Introduction to the pom.xml file
The pom.xml file is the configuration file of a Maven project, which defines the dependencies, plugins, and build rules of the project. Maven is a Java project management tool that can automatically download dependencies, compile, and package projects.
The code in the pom.xml file in this topic mainly includes the following parts:
File declaration statement.
This statement declares that the file is an XML file using XML version
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure the 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 group ascom.example. - Use
<artifactId>to specify the project name ashikaricp-oceanbase-client. - Use
<version>to specify the project version as1.0-SNAPSHOT.
Sample code:
<groupId>com.example</groupId> <artifactId>hikaricp-oceanbase-client</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the properties of the project source files.
Specify the Maven compiler plugin as
maven-compiler-plugin, and set the source code and target Java versions to 8. This means that 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 setting 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.
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 on which the project depends.
Add the
oceanbase-clientdependency library for interacting with the database:- Use
<groupId>to specify the dependency group ascom.oceanbase. - Use
<artifactId>to specify the dependency name asoceanbase-client. - Use
<version>to specify the dependency version as2.4.2.
Note
This part of the code defines the project's dependency on OceanBase Connector/J V2.4.2. For information about other versions, see OceanBase JDBC driver.
Sample code:
<dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency>- Use
Add the
HikariCPdependency library for implementing a high-performance JDBC connection pool:- Use
<groupId>to specify the dependency group ascom.zaxxer. - Use
<artifactId>to specify the dependency name asHikariCP. - Use
<version>to specify the dependency version as3.3.1.
Sample code:
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.3.1</version> </dependency>- Use
Add the
logback-classicdependency library for convenient logging and management:- Use
<groupId>to specify the dependency group asch.qos.logback. - Use
<artifactId>to specify the dependency name aslogback-classic. - Use
<version>to specify the dependency version as1.2.5.
Sample code:
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.5</version> </dependency>- Use
db.properties code
db.properties is the connection pool configuration file in the example. It contains the configuration properties of the connection pool, including the database URL, username, password, and other optional parameters of the connection pool.
The code in the db.properties file in this topic mainly includes the following parts:
Configure the database connection parameters.
- Configure the database connection URL, including the host IP address, port number, and schema to be accessed.
- Configure the database username.
- Configure the database password.
Sample code:
jdbcUrl=jdbc:oceanbase://$host:$port/$schema_name username=$user_name password=$passwordParameter description:
$host: the value of the-hparameter in the connection string. It specifies the connection address of the cloud database of OceanBase Cloud.$port: the value of the-Pparameter in the connection string. It specifies the connection port of the cloud database of OceanBase Cloud.$schema_name: the value of the-Dparameter in the connection string. It specifies the name of the database to be accessed.$user_name: the value of the-uparameter in the connection string. It specifies the account name.$password: the value of the-pparameter in the connection string. It specifies the account password.
Configure other parameters of the connection pool.
- Enable the cache for precompiled SQL statements.
- Set the cache size of precompiled SQL statements to 250.
- Set the maximum lifecycle of a connection to 1800000 milliseconds (30 minutes). If a connection exceeds this time, it will be closed.
- Set the idle timeout of a connection to 600000 milliseconds (10 minutes). If a connection exceeds this time and is idle, it will be closed.
- Set the timeout of a connection to 30000 milliseconds (30 seconds). If a connection is not obtained within this time, an exception will be thrown.
Sample code:
dataSource.cachePrepStmts=true dataSource.prepStmtCacheSize=250 dataSource.maxLifetime=1800000 dataSource.idleTimeout=600000 dataSource.connectionTimeout=30000
Notice
The specific configuration of the parameters depends on the project requirements and the characteristics of the database. We recommend that you adjust and configure the parameters based on your actual situation. For more information about the HikariCP connection pool parameters, see Configuration.
Common basic parameters of the HikariCP connection pool:
| Category | Parameter | Default value | Description |
|---|---|---|---|
| Required parameters | dataSourceClassName | N/A | The name of the DataSource class provided by the JDBC driver.
Notice
|
| jdbcUrl | N/A | The URL for connecting to the database using JDBC. | |
| username | N/A | The username used to connect to the database. | |
| password | N/A | The password used to connect to the database. | |
| Common optional parameters | autoCommit | true | Controls the default auto-commit behavior of the connections returned by the connection pool. |
| connectionTimeout | 30000 | Controls the maximum waiting time for a client to obtain a connection from the connection pool. The unit is milliseconds, and the default value is 30000 (30 seconds). The minimum acceptable connection timeout is 250 milliseconds. | |
| idleTimeout | 600000 | Controls the maximum idle time of a connection in the pool. The unit is milliseconds, and the default value is 600000 (10 minutes). This setting has the following limitations:
|
|
| keepaliveTime | 0 | Controls the frequency of connection keepalive to prevent connections from being timed out by the database or network infrastructure. The unit is milliseconds, and the default value is 0, which means that connection keepalive is disabled. This value must be less than the value of the maxLifetime parameter. |
|
| maxLifetime | 1800000 | Controls the maximum lifecycle of a connection in the connection pool. Used connections will not be automatically recycled. Connections will only be removed from the connection pool when they are closed. The unit is milliseconds, and the default value is 1800000 (30 minutes). If maxLifetime is set to 0, it means that there is no maximum lifecycle limit for connections in the connection pool, i.e., the lifecycle of a connection is infinite. |
|
| connectionTestQuery | N/A | Specifies the connection test query sent by the connection pool to the database. It is executed before a connection is obtained from the connection pool to verify whether the connection to the database is still valid. | |
| minimumIdle | N/A | Controls the minimum number of idle connections to be kept in the connection pool. If the number of idle connections is less than this value and the total number of connections in the connection pool is less than maximumPoolSize, HikariCP will try to quickly and efficiently add additional connections. By default, the value of the minimumIdle parameter is the same as the value of the maximumPoolSize parameter. |
|
| maximumPoolSize | 10 | Controls the maximum size of the connection pool, including idle and active connections. This value determines the maximum number of actual connections to the database backend. | |
| poolName | N/A | The name of the user-defined connection pool. This name is mainly used to identify the connection pool and its configuration in log records and the JMX management console. By default, a name is automatically generated. |
Main.java code
The Main.java file is part of the sample program and demonstrates how to obtain a database connection using the HikariCP connection pool and perform a series of database operations, including creating a table, inserting data, deleting data, updating data, querying data, and printing the query results.
The code in the Main.java file mainly includes the following parts:
Import the required classes and packages.
- Define the package name of the current Java file as
com.exampleto organize and manage Java classes. - Import the
java.sql.Connectionclass to establish and manage a connection to the database. - Import the
java.sql.PreparedStatementclass to execute precompiled SQL statements. - Import the
java.sql.ResultSetclass to process query result sets. - Import the
java.sql.SQLExceptionclass to handle SQL exceptions. - Import the
HikariConfigclass from HikariCP to configure the HikariCP connection pool. - Import the
HikariDataSourceclass from HikariCP to create and manage the HikariCP connection pool.
Code:
package com.example; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource;- Define the package name of the current Java file as
Define the class name and method.
Define a Main class, where the
mainmethod serves as the entry point of the program. In themainmethod, read thedb.propertiesfile to configure the HikariCP connection pool and obtain a database connection. Then, call a series of methods to create a table, insert data, query data, update data, and delete data. If anSQLExceptionoccurs during the operation, the exception's stack trace is printed. The specific steps are as follows:- Define a public class named Main.
- Define the entry method
mainof the Main class. - Create a HikariConfig object and configure it using the specified
db.propertiesfile. - Create a HikariDataSource object and obtain a database connection within the
try-with-resourcesblock. - Call the method for creating a table and pass the obtained database connection object to create the
test_hikaricptable. - Call the method for inserting data and pass the obtained database connection object and data parameters to insert two rows of data,
(1,'A1')and(2,'A2'). - Call the method for querying data and pass the obtained database connection object to check the data insertion status.
- Call the method for updating data and pass the obtained database connection object and update parameters to update the value of the
namecolumn in the row withidequal to1totest_update. - Call the method for querying data and pass the obtained database connection object to check the data update status.
- Call the method for deleting data and pass the obtained database connection object and deletion parameters to delete the row with
idequal to2. - Call the method for querying data and pass the obtained database connection object to check the data deletion status.
- If an
SQLExceptionoccurs in thetryblock, the exception's stack trace is printed. - Define methods for creating a table, inserting data, querying data, updating data, and deleting data.
Code:
public class Main { public static void main(String[] args) { try { HikariConfig config = new HikariConfig("/db.properties"); try (HikariDataSource dataSource = new HikariDataSource(config); Connection conn = dataSource.getConnection()) { createTable(conn); insertData(conn, 1, "A1"); insertData(conn, 2, "A2"); selectData(conn); updateData(conn, "test_update", 1); selectData(conn); deleteData(conn, 2); selectData(conn); } } catch (SQLException e) { e.printStackTrace(); } } // Define the method for creating a table. // Define the method for inserting data. // Define the method for querying data. // Define the method for updating data. // Define the method for deleting data. }Define the method for creating a table.
Define a private static method
createTableto create a table namedtest_hikaricpin the database, which containsidandnamecolumns. The specific steps are as follows:- Define a private static method
createTablethat accepts a Connection object as a parameter and declares that it may throw anSQLException. - Define an SQL statement string to create a table named
test_hikaricpwithid(data typeNUMBER) andname(data typeVARCHAR2(50)) columns. - Use the connection object
connto create a precompiled SQL statement objectpstmtand use it within thetry-with-resourcesblock. - Execute the SQL statement to create the
test_hikaricptable. - Print a message to the console indicating that the table was created successfully.
Code:
private static void createTable(Connection conn) throws SQLException { String sql = "CREATE TABLE test_hikaricp (id NUMBER, name VARCHAR2(50))"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.executeUpdate(); System.out.println("Table created successfully."); } }- Define a private static method
Define the method for inserting data.
Define a private static method
insertDatato insert data into thetest_hikaricptable in the database. The specific steps are as follows:- Define a private static method
insertDatathat accepts a Connection object, an integeridparameter, and a stringnameparameter, and declares that it may throw anSQLException. - Define an SQL statement string to insert data into the
test_hikaricptable, includingidandnamecolumns. - Use the connection object
connto create a precompiled SQL statement objectpstmtand use it within thetry-with-resourcesblock. - Set the value of the first parameter
?in the SQL statement toid. - Set the value of the second parameter
?in the SQL statement toname. - Execute the SQL statement to insert data into the table.
- Print a message to the console indicating that the data was inserted successfully.
Code:
private static void insertData(Connection conn, int id, String name) throws SQLException { String sql = "INSERT INTO test_hikaricp (id, name) VALUES (?, ?)"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, id); pstmt.setString(2, name); pstmt.executeUpdate(); System.out.println("Data inserted successfully."); } }- Define a private static method
Define the method for querying data.
Define a private static method
selectDatato query data from thetest_hikaricptable in the database. The specific steps are as follows:- Define a private static method
selectDatathat accepts a Connection object as a parameter and declares that it may throw aSQLException. - Define a SQL statement string for querying all data from the
test_hikaricptable. - Use the
connconnection object to create a precompiled SQL statement objectpstmtand use it within atry-with-resourcesblock. Additionally, execute the SQL query by calling theexecuteQuery()method and return the result set objectrs. - Print a message to the console indicating that user data is being printed.
- Traverse the result set, using the
next()method to check if there is another row of data in the result set. If there is, enter the loop. - Retrieve the value of the
idcolumn from the result set and assign it to the variableid. - Retrieve the value of the
namecolumn from the result set and assign it to the variablename. - Print the
idandnamevalues of each row to the console. - Print an empty line to the console.
Sample code:
private static void selectData(Connection conn) throws SQLException { String sql = "SELECT * FROM test_hikaricp"; try (PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery()) { System.out.println("User Data:"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } System.out.println(); } }- Define a private static method
Define a method for updating data.
Define a private static method
updateDatafor updating data in thetest_hikaricptable in the database. The specific steps are as follows:- Define a private static method
updateDatathat accepts a Connection object, a string-typenameparameter, and an integer-typeidparameter, and declares that it may throw aSQLException. - Define a SQL statement string for updating data in the
test_hikaricptable, setting the value of thenamecolumn to the specifiednamewhere the value of theidcolumn is equal to the specifiedid. - Use the
connconnection object to create a precompiled SQL statement objectpstmtand use it within atry-with-resourcesblock. - Set the value of the first parameter
?in the SQL statement toname. - Set the value of the second parameter
?in the SQL statement toid. - Execute the SQL statement to update the data in the table.
- Print a message to the console indicating that the data update was successful.
Sample code:
private static void updateData(Connection conn, String name, int id) throws SQLException { String sql = "UPDATE test_hikaricp SET name = ? WHERE id = ?"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, name); pstmt.setInt(2, id); pstmt.executeUpdate(); System.out.println("Data updated successfully."); } }- Define a private static method
Define a method for deleting data.
Define a private static method
deleteDatafor deleting data from thetest_hikaricptable in the database that meets the specified conditions. The specific steps are as follows:- Define a private static method
deleteDatathat accepts a Connection object and an integer-typeidparameter, and declares that it may throw aSQLException. - Define a SQL statement string for deleting data from the
test_hikaricptable where the value of theidcolumn is equal to the specifiedid. - Use the
connconnection object to create a precompiled SQL statement objectpstmtand use it within atry-with-resourcesblock. - Set the value of the first parameter
?in the SQL statement toid. - Execute the SQL statement to delete data that meets the specified conditions from the table.
- Print a message to the console indicating that the data deletion was successful.
Sample code:
private static void deleteData(Connection conn, int id) throws SQLException { String sql = "DELETE FROM test_hikaricp WHERE id = ?"; try (PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, id); pstmt.executeUpdate(); System.out.println("Data deleted successfully."); } }- Define a private static method
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.oceanbase</groupId>
<artifactId>hikaricp-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>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
</project>
jdbcUrl=jdbc:oceanbase://$host:$port/$schema_name
username=$user_name
password=$password
dataSource.cachePrepStmts=true
dataSource.prepStmtCacheSize=250
dataSource.maxLifetime=1800000
dataSource.idleTimeout=600000
dataSource.connectionTimeout=30000
package com.example;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class Main {
public static void main(String[] args) {
try {
HikariConfig config = new HikariConfig("/db.properties");
try (HikariDataSource dataSource = new HikariDataSource(config);
Connection conn = dataSource.getConnection()) {
createTable(conn);
insertData(conn, 1, "A1");
insertData(conn, 2, "A2");
selectData(conn);
updateData(conn, "test_update", 1);
selectData(conn);
deleteData(conn, 2);
selectData(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void createTable(Connection conn) throws SQLException {
String sql = "CREATE TABLE test_hikaricp (id NUMBER, name VARCHAR2(50))";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.executeUpdate();
System.out.println("Table created successfully.");
}
}
private static void insertData(Connection conn, int id, String name) throws SQLException {
String sql = "INSERT INTO test_hikaricp (id, name) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.executeUpdate();
System.out.println("Data inserted successfully.");
}
}
private static void selectData(Connection conn) throws SQLException {
String sql = "SELECT * FROM test_hikaricp";
try (PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
System.out.println("User Data:");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
System.out.println();
}
}
private static void updateData(Connection conn, String name, int id) throws SQLException {
String sql = "UPDATE test_hikaricp SET name = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, id);
pstmt.executeUpdate();
System.out.println("Data updated successfully.");
}
}
private static void deleteData(Connection conn, int id) throws SQLException {
String sql = "DELETE FROM test_hikaricp WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
System.out.println("Data deleted successfully.");
}
}
}
References
- For more information about OceanBase Connector/J, see OceanBase Connector/J.
- For more information about HikariCP, see HikariCP.