This topic introduces how to build an application by using the SpringBoot framework and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, data query, and other basic operations.
Prerequisites
- You have installed OceanBase Database.
- You have installed JDK 1.8 and Maven.
- You have installed IntelliJ IDEA.
Note
The tool used to run the sample code in this topic is IntelliJ IDEA 2021.3.2 (Community Edition). You can also choose a tool of your preference to run the sample 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.
- Obtain the connection information of OceanBase Database.
- Import the
java-oceanbase-springbootproject into IntelliJ IDEA. - Modify the database connection information in the
java-oceanbase-springbootproject. - Run the
java-oceanbase-springbootproject.
Step 1: Obtain the connection information of OceanBase Database
Contact the deployment personnel or administrator of OceanBase Database to obtain the corresponding database connection information.
obclient -hxx.xx.xx.xx -P2883 -uroot@sys#cluster -p**** -AFill in the URL below based on the OceanBase Database that has been deployed.
Note
The URL is required in the
application.propertiesfile.jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$password&useSSL=false&useUnicode=true&characterEncoding=utf-8Parameter description:
host: the IP address for connecting to OceanBase Database. For connection through ODP, use the IP address of an ODP. For direct connection, use the IP address of an OBServer node.port: 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_name: the name of the schema to be accessed.user_name: the username specified after the-uparameter. The format is username@tenant name#cluster name or username@SERVICE:service name. If you use the format username@tenant name#cluster name, the default tenant issysand the default administrator isroot. When you use direct connection, you can omit the cluster name. However, when you use connection through ODP, you must specify the cluster name. The username and password of the account must have the privilege to access the specified schema.password: the password of the account.useSSL=false&useUnicode=true&characterEncoding=utf-8: the additional connection properties.useSSL: specifies whether to useSSL/TLSfor forced connections. Default value:false.useUnicode: specifies the encoding and decoding format for characters. Default value:true.characterEncoding: specifies the character encoding supported by the database URL option. Default value:utf8.
For more information about URL parameters, see Database URL.
Step 2: Import the java-oceanbase-springboot project into IntelliJ IDEA
Start IntelliJ IDEA and choose File > Open....

In the Open File or Project window, select the project files and click OK to import the files.
IntelliJ IDEA automatically recognizes the files and displays the directory structure, file list, module list, dependency relationships, and other details of the project in the Project window. The Project window is usually located on the left side of the IntelliJ IDEA interface and is generally open by default. If the Project window is closed, you can reopen it by choosing View > Tool Windows > Project in the menu bar or by using the shortcut Alt + 1.
Note
When you import a project using IntelliJ IDEA, it will automatically detect the pom.xml file in the project, download the required dependency libraries based on the described dependencies in the file, and add them to the project.
View the project.

Step 3: Modify the database connection information in the java-oceanbase-springboot project
Modify the database connection information in the application.properties file based on the information obtained in Step 1: Obtain the connection information of OceanBase Database.
Here is an example:
- The name of the database driver is:
com.mysql.cj.jdbc.Driver. - The IP address of the OBServer node is
10.10.10.1. - The port is 2881.
- The name of the database to be accessed is
test. - The tenant account is
root@mysq001, wheremysql001is a MySQL user tenant created in OceanBase Database, androotis the username of themysql001tenant. - The password is
******.
Sample code:
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:oceanbase://10.10.10.1:2881/test?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root@mysq001
spring.datasource.password=******
Step 4: Run the java-oceanbase-springboot project
Running path
- In the project structure, locate the src > test > java path and find the
TestSpringbootApplicationTests.javafile. - From the toolbar, choose Run(U) > Run > TestSpringbootApplicationTests or simply click the green triangle in the upper right corner.
- In the console of IntelliJ IDEA, view the project logs and output results.
Running result
test_springboot delete successfully!
test_springboot create successfully!
user = User{id=2, name='update'}
User{id=2, name='update'}
User{id=3, name='insert3'}
User{id=4, name='insert4'}
User{id=5, name='insert5'}
User{id=6, name='insert6'}
User{id=7, name='insert7'}
User{id=8, name='insert8'}
User{id=9, name='insert9'}
User{id=10, name='insert10'}
FAQ
1. Connection timeout
If a connection timeout occurs, you can specify the connection timeout period in the JDBC URL:
jdbc:mysql://host:port/database?connectTimeout=30000&socketTimeout=60000
2. Character set issue
To ensure correct character encoding, set the character set in the JDBC URL:
jdbc:mysql://host:port/database?characterEncoding=utf8&useUnicode=true
3. SSL connection
To establish an SSL connection with OceanBase Database, add the following parameter to the JDBC URL:
jdbc:mysql://host:port/database?useSSL=true&requireSSL=true
4. Special characters in account name or password
If the username or password contains special characters such as #, URL encode the username or password:
String encodedPassword = URLEncoder.encode(password, "UTF-8");
Notice
When you use MySQL Connector/J 8.x, make sure that the account name and password do not contain the number sign (#). Otherwise, a connection error may occur.
Project code introduction
Click java-oceanbase-springboot to download the project code, which is a compressed file named java-oceanbase-springboot.
After decompressing it, you will find a folder named java-oceanbase-springboot. The directory structure is as follows:
│--pom.xml
│
├─.idea
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─oceanbase
│ │ │ └─testspringboot
│ │ │ │--TestSpringbootApplication.java
│ │ │ │
│ │ │ ├─dao
│ │ │ │ │--UserDao.java
│ │ │ │ │
│ │ │ │ └─impl
│ │ │ │ └─--UserDaoImpl.java
│ │ │ │
│ │ │ └─entity
│ │ │ └─--User.java
│ │ │
│ │ └─resources
│ │ └─--application.properties
│ │
│ └─test
│ └─java
│ └─com
│ └─oceanbase
│ └─testspringboot
│ └─--TestSpringbootApplicationTests.java
│
└─target
File description:
pom.xml: the configuration file of the Maven project, which contains the dependencies, plugins, and build details of the project..idea: the directory used for storing project-related configuration information in the Integrated Development Environment (IDE).src: a directory that is generally used to store the source code of a project.main: a directory that stores the main source code and resource files.java: a directory that stores the Java source code.com: the root directory that stores the Java package.oceanbase: the root directory that stores the project.testspringboot: the root directory of the Java package, which contains all the Java classes of the project.TestSpringbootApplication.java: the main class of the project, which contains the main method.dao: a directory that stores the Data Access Object (DAO) packages for accessing databases or other data storage services.UserDao.java: the user DAO, which is used for performing CRUD operations on user data.impl: a directory that stores the implementations of the DAO interfaces.UserDaoImpl.java: the implementation class of the user DAO interface.entity: a directory that stores the entity classes, which are the Java classes corresponding to the database tables.User.java: the persistent object of users, which is used for mapping the fields of the user data table.resources: a directory that stores the resource files, such as configuration files and SQL files.application.properties: the configuration file of the project, which is used for configuring the properties and parameters of the application.test: a directory that stores the test code and resource files.TestSpringbootApplicationTests.java: a Java class that stores the test code for Spring Boot.target: a directory that stores the compiled class files and JAR packages.
Introduction to pom.xml
Note
If you just want to verify the sample, you can use the default code without modification. You can also modify the pom.xml file based on the following introduction.
The content of the pom.xml configuration file is as follows:
Declaration statement.
Declare this file to be an XML file that uses XML standard
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure the namespaces and the 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.0, and the URI of the corresponding XSD file ashttps://maven.apache.org/xsd/maven-4.0.0.xsd. - Use
<modelVersion>to specify the POM model version 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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> </project>- Use
Configure the parent information.
- Use
<groupId>to specify the parent group ID asorg.springframework.boot. - Use
<artifactId>to specify the parent artifact ID asspring-boot-starter-parent. - Use
<version>to specify the parent version as2.7.11. - Use
relativePathto indicate that the parent path is empty.
Sample code:
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.11</version> <relativePath/>- Use
Configure basic information.
- Use
<groupId>to specify the project group ID ascom.oceanbase. - Use
<artifactId>to specify the project artifact ID asjava-oceanbase-springboot. - Use
<version>to specify the project version as0.0.1-SNAPSHOT. - Use
descriptionto describe the project asDemo project for Spring Boot.
Sample code:
<groupId>com.oceanbase</groupId> <artifactId>java-oceanbase-springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>java-oceanbase-springboot</name> <description>Demo project for Spring Boot</description>- Use
Configure the Java version.
Specify the Java version for the project as 1.8.
Sample code:
<properties> <java.version>1.8</java.version> </properties>Configure core dependencies.
Specify the dependency group ID as
org.springframework.boot, the artifact ID asspring-boot-starter, and the dependency library contains component dependencies that are supported by default in Spring Boot, including web, data processing, security, and test features.Sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>Specify the dependency group ID as
org.springframework.boot, the artifact ID asspring-boot-starter-jdbc, and the dependency allows you to use JDBC-related features provided by Spring Boot, such as connection pools and data source configurations.Sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>Specify the dependency group ID as
org.springframework.boot, the artifact ID asspring-boot-starter-test, and the scope astest. The dependency allows you to use test frameworks and tools provided by Spring Boot, such as JUnit, Mockito, and Hamcrest.Sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>Specify the dependency group ID as
com.oceanbase, the artifact ID asoceanbase-client, and the version as2.4.3. The dependency allows you to use client features provided by OceanBase Database, such as connection, query, and transaction.Sample code:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.3</version> </dependency> </dependencies>
Configure the Maven plugin.
Specify the dependency group ID as
org.springframework.boot, and the artifact ID asspring-boot-maven-plugin. The plugin is used to package a Spring Boot application into an executable JAR or WAR file, and you can run the file directly.Sample code:
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
application.properties code
The application.properties file configures the data source for the Spring Boot application and specifies the driver class name, URL, username, and password required to connect to OceanBase Database. With these configurations, the application can connect to and operate OceanBase Database.
The value of
spring.datasource.driverClassNameis set tocom.oceanbase.jdbc.Driver, which specifies the database driver for connecting to OceanBase Database.The value of
spring.datasource.urlis the URL for connecting to the database.The value of
spring.datasource.usernameis the username for connecting to the database.The value of
spring.datasource.passwordis the password for connecting to the database.Sample code:
spring.datasource.driverClassName=com.oceanbase.jdbc.Driver spring.datasource.url=jdbc:oceanbase://host:port/schema_name?useSSL=false&useUnicode=true&characterEncoding=utf-8 spring.datasource.username=user_name spring.datasource.password=******
Introduction to UserDaoImpl.java
The UserDaoImpl.java file uses a JdbcTemplate object to execute SQL statements for inserting, deleting, updating, and querying data in the user table.
The code in the UserDaoImpl.java file consists of the following parts:
Reference other classes and interfaces.
Declare the package name of the current file as
com.oceanbase.testspringboot.dao.impl, which contains the following interfaces and classes:UserDao: the interface for implementing the methods defined in the UserDao interface.User: a class for passing and storing user data.Autowired: a annotation for injecting the JdbcTemplate object into this class to execute SQL statements.BeanPropertyRowMapper: a class for mapping the query result set from the database into a list of Java objects.JdbcTemplate: a class for executing SQL statements and handling database access.Repository: a annotation used to mark the Spring Data repository component.List: an interface for operating on the query result collection.
Sample code:
import com.oceanbase.testspringboot.dao.UserDao; import com.oceanbase.testspringboot.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List;Define the
UserDaoImplclass.Use the
Repositoryannotation to specify theBeanname of this class asuserDao, and use theJdbcTemplateobject to insert, delete, update, and query data in theUsertable by executing SQL statements.Insert user information.
Call the
insertmethod of theJdbcTemplateobject to insert the ID and name of a user into thetest_springboottable in the database. The method then returns a boolean value that indicates the result of the insertion operation.Sample code:
@Autowired private JdbcTemplate jdbcTemplate; //Jdbc connection tool class @Override public boolean insertUser(User user) { String sql = "insert into test_springboot(id,name)values(?,?)"; Object[] params = {user.getId(), user.getName()}; return jdbcTemplate.update(sql, params) > 0; }Delete user information.
Call the
deletemethod of theJdbcTemplateobject to delete a user from the database based on the user ID. The method then returns a boolean value that indicates the result of the deletion operation.Sample code:
@Override public boolean deleteById(Long id) { String sql = "delete from test_springboot where id=?"; Object[] params = {id}; return jdbcTemplate.update(sql, params) > 0; }Update user information.
Call the
updatemethod of theJdbcTemplateobject to update the name of a user in thetest_springboottable in the database based on the user ID. The method then returns a boolean value that indicates the result of the update operation.Sample code:
@Override public boolean updateUser(User user) { String sql = "update test_springboot set name=? where id=?"; Object[] params = {user.getName(), user.getId()}; return jdbcTemplate.update(sql, params) > 0; }Query user information.
Use the
JdbcTemplateobject to execute an SQL query statement to query the user record with the specified ID from thetest_springboottable. Then, use theBeanPropertyRowMapperclass to map the query result set to a Java object. The method returns the query result object.Sample code:
@Override public User selectUserById(Long id) { String sql = "select * from test_springboot where id=?"; Object[] params = new Object[]{id}; return jdbcTemplate.queryForObject( sql, params, new BeanPropertyRowMapper<>(User.class)); }Query all user information.
Call the
querymethod of theJdbcTemplateobject to query all users from the database and map the query result to a list of User objects, which is then returned.Sample code:
@Override public List<User> selectAllUsers() { String sql = "select * from test_springboot"; return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); }
UserDao.java file introduction
The UserDao.java file uses the UserDao interface to define methods for operating user data.
The code in the UserDao.java file mainly consists of the following sections:
Reference other classes and interfaces.
Declare the name of the package to which the current file belongs as
package com.oceanbase.testspringboot.dao, which contains the following interfaces and classes:Userclass: used to pass and store user data.Listinterface: used to operate the query result set.
Sample code:
import com.oceanbase.testspringboot.entity.User; import java.util.List;Define the UserDao interface.
Use the UserDao interface to define methods for operating user data. The methods include inserting user information, deleting user information, updating user information, querying user information by user ID, and querying all user information.
Sample code:
public interface UserDao { boolean insertUser(User user); boolean deleteById(Long id); boolean updateUser(User user); User selectUserById(Long id); List<User> selectAllUsers(); }
User.java file introduction
The User.java file defines the User class to represent a user object.
Declare the
Userobject. Declare theUserclass to contain two private fields:idandname. Also, provide a no-argument constructor. Operate user information by setting and getting the values of theidandnamefields.Sample code:
private Long id; private String name; public User() { }Create a
Userobject. Define the parameterized constructor of theUserclass to create aUserobject with specifiedidandnamevalues.Sample code:
public User(Long id, String name) { this.id = id; this.name = name; }Get and set the
idandnamevalues. Define four methods in theUserclass to get and set the values of theidandnameattributes. ThegetIdmethod is used to get theidvalue, and thesetIdmethod is used to set theidvalue. ThegetNamemethod is used to get the usernamename. ThesetNamemethod is used to set the usernamename.Sample code:
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }Return the string representation of the
Userobject.Rewrite the
toStringmethod in theUserclass to return the string representation of theUserobject. Annotate the method with@Overrideto override the same-named method in the parent class. Define thetoStringmethod to return the string representation of theUserobject. Concatenating the values of theidandnameattributes, format them into a string, and return the string to the callerUserobject.Sample code:
@Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; }
Introduction to TestSpringbootApplication.java
The TestSpringbootApplication.java file starts a Spring Boot application by using the UserDao interface.
The code in the TestSpringbootApplication.java file consists of the following parts:
Define classes and interfaces.
Specify the package name of the current file as
com.oceanbase.testspringbootand include the following interfaces and classes:SpringApplicationclass: used to start a Spring Boot application.@SpringBootApplicationannotation: indicates that this class is the entry point of the Spring Boot application.
Sample code:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;Define the
TestSpringbootApplicationclass.Identify this class as the entry class of the Spring Boot application by using the SpringBootApplication annotation. You can call the run method of the SpringApplication class to start the Spring Boot application.
Sample code:
@SpringBootApplication public class TestSpringbootApplication { public static void main(String[] args) { SpringApplication.run(TestSpringbootApplication.class, args); } }
Introduction to TestSpringbootApplicationTests.java
The TestSpringbootApplicationTests.java file starts a Spring Boot application by using the UserDao interface.
The code in the TestSpringbootApplicationTests.java file consists of the following sections:
Reference other classes and interfaces.
Declare the current file to belong to the
com.oceanbase.testspringbootpackage, which contains the following interfaces and classes:UserDaointerface: implements the methods defined in theUserDaointerface.Userclass: used to pass and store user data.Testannotation: identifies a test method.Autowiredannotation: injects a JdbcTemplate object into the class for executing SQL statements.SpringBootTestannotation: identifies the class as a Spring Boot test class.JdbcTemplateclass: used to execute SQL statements and handle database access.Listinterface: used to operate on the query result set.
Sample code:
import com.oceanbase.testspringboot.dao.UserDao; import com.oceanbase.testspringboot.entity.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List;Define the
TestSpringbootApplicationTestsclass.Use the
SpringBootTestannotation to identify the class for testing features in a Spring Boot application. Use theUserDaoandJdbcTemplateobjects to perform CRUD operations on user data and output the results.Define objects.
Use the
@Autowiredannotation to automatically inject theUserDaoandJdbcTemplateobjects.Sample code:
@Autowired private UserDao userDao; @Autowired private JdbcTemplate jdbcTemplate;Define the
contextLoadsmethod.Use the
contextLoadsmethod as the specific implementation of the test method.Drop the
test_springboottable.Use the
jdbcTemplate.executemethod to execute thedrop table test_springbootSQL statement and drop thetest_springboottable.Sample code:
try { jdbcTemplate.execute("drop table test_springboot"); System.out.println("test_springboot delete successfully!"); }Create the
test_springboottable.Use the
jdbcTemplate.executemethod to execute thecreate table test_springboot (id int primary key, name varchar(50))SQL statement and create atest_springboottable that contains theidandnamefields.Sample code:
catch (Exception ignore) { } finally { jdbcTemplate.execute("create table test_springboot (" + "id int primary key," + "name varchar(50))"); System.out.println("test_springboot create successfully!"); }Insert data.
Use the
userDao.insertUsermethod to insert 10 user data records into thetest_springboottable. Theidfield ranges from 1 to 10, and thenamefield stores values of `"insert" + i'.Sample code:
for (int i = 1; i <= 10; i++) { userDao.insertUser(new User((long) i, "insert" + i)); }Delete data.
Use the
userDao.deleteByIdmethod to delete the user data record whoseidis 1.Sample code:
userDao.deleteById(1L);Update data.
Use the
userDao.updateUsermethod to update the user data record whoseidis 2. Change the value of thenamefield toupdate.Sample code:
userDao.updateUser(new User(2L, "update"));Query data.
Use the
userDao.selectUserByIdmethod to query the user data record whoseidis 2 and print the query result.Sample code:
User user = userDao.selectUserById(2L); System.out.println("user = " + user);Query all data.
Use the
userDao.selectAllUsersmethod to query all user data records in thetest_springboottable and print the query result.Sample code:
List<User> userList = userDao.selectAllUsers(); userList.forEach(System.out::println);
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 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.11</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.oceanbase</groupId>
<artifactId>java-oceanbase-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>java-oceanbase-springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:oceanbase://host:port/schema_name?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=user_name
spring.datasource.password=******
package com.oceanbase.testspringboot.dao.impl;
import com.oceanbase.testspringboot.dao.UserDao;
import com.oceanbase.testspringboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate; //Jdbc connection tool class
@Override
public boolean insertUser(User user) {
String sql = "insert into test_springboot(id,name)values(?,?)";
Object[] params = {user.getId(), user.getName()};
return jdbcTemplate.update(sql, params) > 0;
}
@Override
public boolean deleteById(Long id) {
String sql = "delete from test_springboot where id=?";
Object[] params = {id};
return jdbcTemplate.update(sql, params) > 0;
}
@Override
public boolean updateUser(User user) {
String sql = "update test_springboot set name=? where id=?";
Object[] params = {user.getName(), user.getId()};
return jdbcTemplate.update(sql, params) > 0;
}
@Override
public User selectUserById(Long id) {
String sql = "select * from test_springboot where id=?";
Object[] params = new Object[]{id};
return jdbcTemplate.queryForObject(
sql,
params,
new BeanPropertyRowMapper<>(User.class));
}
@Override
public List<User> selectAllUsers() {
String sql = "select * from test_springboot";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
}
}
package com.oceanbase.testspringboot.dao;
import com.oceanbase.testspringboot.entity.User;
import java.util.List;
public interface UserDao {
boolean insertUser(User user);
boolean deleteById(Long id);
boolean updateUser(User user);
User selectUserById(Long id);
List<User> selectAllUsers();
}
package com.oceanbase.testspringboot.entity;
public class User {
private Long id;
private String name;
public User() {
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
package com.oceanbase.testspringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringbootApplication.class, args);
}
}
package com.oceanbase.testspringboot;
import com.oceanbase.testspringboot.dao.UserDao;
import com.oceanbase.testspringboot.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
@SpringBootTest
class TestSpringbootApplicationTests {
@Autowired
private UserDao userDao;
@Autowired
private JdbcTemplate jdbcTemplate; //Jdbc connection tool class
@Test
void contextLoads() {
try {
// Use the execute() method to execute SQL statements and delete the user table test_springboot
jdbcTemplate.execute("drop table test_springboot");
System.out.println("test_springboot delete successfully!");
} catch (Exception ignore) {
} finally {
// Use the execute() method to execute SQL statements and create user table tests_ user
jdbcTemplate.execute("create table test_springboot (" +
"id int primary key," +
"name varchar(50))");
System.out.println("test_springboot create successfully!");
}
//UserDao userDao=new UserDaoImpl();
//ApplicationContext ioc=new ApplicationContext("/appli");`
//add
for (int i = 1; i <= 10; i++) {
userDao.insertUser(new User((long) i, "insert" + i));
}
//delete
userDao.deleteById(1L);
//update
userDao.updateUser(new User(2L, "update"));
//selectUserById
User user = userDao.selectUserById(2L);
System.out.println("user = " + user);
//query all users
List<User> userList = userDao.selectAllUsers();
userList.forEach(System.out::println);
}
}
References
For more information about OceanBase Connector/J, see OceanBase Connector/J.

Download the java-oceanbase-springboot sample project