This topic describes how to use the SpringDataJPA framework and OceanBase Cloud to build an application that can perform basic operations such as creating tables, inserting data, and querying data.
Prerequisites
- You have registered an account for OceanBase Cloud and created an instance and a MySQL compatible tenant. For more information, see Create an instance and Create a tenant.
- You have installed JDK 1.8 and Maven.
- You have installed IntelliJ IDEA.
Note
The code in this topic is run in IntelliJ IDEA 2021.3.2 (Community Edition). You can also use your preferred tool to run the sample code.
Procedure
Note
The steps in this topic are based on the Windows environment. If you use a different operating system or compiler, the steps may vary.
- Obtain the connection string of the OceanBase Cloud database.
- Import the
java-oceanbase-springdatajpaproject into IDEA. - Modify the database connection information in the
java-oceanbase-springdatajpaproject. - Run the
java-oceanbase-springdatajpaproject.
Step 1: Obtain the connection string of the OceanBase Cloud database
Log in to the OceanBase Cloud console. In the instance list, expand the information of the target instance, and in the target tenant, choose Connect > Get Connection String.
For more information, see Obtain the connection string.
Fill in the corresponding information in the following URL based on the created OceanBase Cloud database.
Note
The URL information is required in the
application.ymlfile.jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$password&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8Parameter description:
host: the connection address of the OceanBase Cloud database, for example,t********.********.oceanbase.cloud.port: the connection port of the OceanBase Cloud database. The default value is 3306.schema_name: the name of the schema to be accessed.user_name: the account for accessing the database.password: the password of the account.characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8: additional connection attributes.characterEncoding: the character encoding supported by the database URL option. The default value isutf8.useSSL: whether to useSSL/TLSwhen connecting. The default value isfalse.serverTimezone: the server time zone. The default value is China Standard Time.
For more information about URL parameters, see Database URL.
Step 2: Import the java-oceanbase-springdatajpa project into IDEA
Open IntelliJ IDEA and choose File > Open....

In the Open File or Project window that appears, select the project file and click OK to import the project file.
IntelliJ IDEA automatically identifies various files in the project and displays the project directory structure, file list, module list, and dependency relationships in the Project tool window. The Project tool window is usually located on the far left of the IntelliJ IDEA interface and is open by default. If it is closed, you can click View > Tool Windows > Project in the menu bar or press the shortcut key Alt + 1 to reopen it.
Note
When you import a project using IntelliJ IDEA, it automatically detects the pom.xml file 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 3: Modify the database connection information in the java-oceanbase-springdatajpa project
Modify the database connection information in the application.yml file based on the information obtained in Step 1: Obtain the connection string of the OceanBase Cloud 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
t5******.********.oceanbase.cloud. - The access port is 3306.
- The name of the schema to be accessed is
test. - The tenant connection account is
mysql001. - The password is
******.
Here is the sample code:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://t5******.********.oceanbase.cloud:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: mysql001
password: ******
type: com.alibaba.druid.pool.DruidDataSource
Step 4: Run the java-oceanbase-springdatajpa project
Run path
- In the project structure, go to src > test > java and find the
TestSpringDataJpaApplicationTests.javafile. - In the tool menu bar, choose Run > Run... > TestSpringDataJpaApplicationTests.contextLoads, or click the green triangle in the upper right corner to run.
- View the project logs and output results in the IDEA console.
Run result
User{id=1, username='insert1'}
User{id=2, username='update'}
User{id=3, username='insert3'}
User{id=4, username='insert4'}
User{id=5, username='insert5'}
FAQ
1. Connection timeout
If you encounter a connection timeout issue, you can configure the connection timeout parameter in the JDBC URL:
jdbc:mysql://host:port/database?connectTimeout=30000&socketTimeout=60000
2. Character set issues
To ensure correct character encoding, set the appropriate character set parameter in the JDBC URL:
jdbc:mysql://host:port/database?characterEncoding=utf8&useUnicode=true
3. SSL connection
To enable an SSL connection to the cloud database of OceanBase Cloud, add the following parameter to the JDBC URL:
jdbc:mysql://host:port/database?useSSL=true&requireSSL=true
4. Special characters in the username or password
If the username or password contains special characters (such as #), you need to URL-encode them:
String encodedPassword = URLEncoder.encode(password, "UTF-8");
Notice
When using MySQL Connector/J 8.x, ensure that the username and password do not contain the # character. Otherwise, you may encounter a connection error.
Project code
Click java-oceanbase-springdatajpa to download the project code, which is a compressed file named java-oceanbase-springdatajpa.
After decompressing it, you will find a folder named java-oceanbase-springdatajpa. The directory structure is as follows:
│--pom.xml
│
├─.idea
│
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─oceanbase
│ │ │ └─testspringdatajpa
│ │ │ │--TestSpringDataJpaApplication.java
│ │ │ │
│ │ │ ├─dao
│ │ │ │ └─UserRepository.java
│ │ │ │
│ │ │ ├─entity
│ │ │ │ └─User.java
│ │ │ │
│ │ │ └─service
│ │ │ │--UserService.java
│ │ │ │
│ │ │ └─impl
│ │ │ └─--UserServiceImpl.java
│ │ │
│ │ └─resources
│ │ │--application.yml
│ │ │
│ │ ├─static
│ │ └─templates
│ └─test
│ └─java
│ └─com
│ └─oceanbase
│ └─testspringdatajpa
│ └─--TestSpringDataJpaApplicationTests.java
│
└─target
File description:
pom.xml: the configuration file of the Maven project, which contains information about the project's dependencies, plugins, and build process..idea: a directory used by the Integrated Development Environment (IDE) to store project-related configuration information.src: a directory typically used to store the source code of the 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 for storing Java packages.oceanbase: the root directory for storing the project.testspringdatajpa: the root directory for storing Java packages, which contains all the Java classes of the project.TestSpringDataJpaApplication.java: the entry class of the Spring Boot application.dao: a directory that stores the Data Access Object (DAO) packages for accessing databases or other data storage services.UserRepository.java: the user data access interface, which defines the operations for adding, deleting, modifying, and querying user data.entity: a directory that stores entity classes corresponding to database tables.User.java: the user persistence object, which maps the fields of the user data table.service: a directory for storing service interface definitions.UserService.java: the user service interface, which defines the methods for operating on user data.impl: a directory for storing the implementation classes of the business logic.UserServiceImpl.java: the implementation class of the user service, which implements the methods defined in the UserService interface.resources: a directory for storing resource files, such as configuration files and SQL files.application.yml: the configuration file of the application, which is used to configure database connections and other information.static: a directory for storing static files, such as CSS and JavaScript files.templates: a directory for storing template files, such as HTML templates.test: a directory for storing test code and resource files.TestSpringDataJpaApplicationTests.java: a class for executing and verifying the functionality related to Spring Data JPA.target: a directory for storing compiled Class files, JAR packages, and other files.
Introduction to the pom.xml file
Note
If you just want to verify the example, you can use the default code without any modifications. You can also follow the instructions below to modify the pom.xml file according to your needs.
The content of the pom.xml configuration file is as follows:
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 namespaces and model version of the POM.
- 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 ashttps://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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>- Use
Configure the parent project information.
- Use
<groupId>to specify the parent project identifier asorg.springframework.boot. - Use
<artifactId>to specify the parent project dependency asspring-boot-starter-parent. - Use
<version>to specify the parent project version as2.7.0. - Use
relativePathto indicate that the parent project path is empty.
Sample code:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.0</version> <relativePath/> </parent>- Use
Configure the basic information.
- Use
<groupId>to specify the project identifier ascom.oceanbase. - Use
<artifactId>to specify the project dependency asjava-oceanbase-springdatajpa. - Use
<version>to specify the project version as0.0.1-SNAPSHOT. - Use
descriptionto introduce the project information asDemo project for Spring Boot.
Sample code:
<groupId>com.oceanbase</groupId> <artifactId>java-oceanbase-springdatajpa</artifactId> <version>0.0.1-SNAPSHOT</version> <name>java-oceanbase-springdatajpa</name> <description>Demo project for Spring Boot</description>- Use
Configure the Java version.
Specify the Java version used by the project as 1.8.
Sample code:
<properties> <java.version>1.8</java.version> </properties>Configure the core dependencies.
Specify the organization as
org.springframework.boot, the name asspring-boot-starter-data-jpa, and the dependency library as containing the necessary dependencies and configurations for data access using JPA. Spring Boot Starter Data JPA is a Spring Boot starter.Sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>Specify the organization as
org.springframework.boot, the name asspring-boot-starter-web, and the dependency library as containing the necessary dependencies and configurations for web development using Spring Boot. It is a Spring Boot starter.Sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>Specify the organization as
org.springframework.boot, the name asspring-boot-starter-test, and the scope astest. This dependency allows you to use the testing framework 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 organization as
com.alibaba, the name asdruid, and the version as1.2.8. This dependency allows you to use the Druid library to manage and optimize the acquisition and release of database connections.Sample code:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency>Specify the organization as
com.oceanbase, the name asoceanbase-client, and the version as2.4.2. This dependency allows you to use the client features provided by OceanBase, such as connection, query, and transaction.Sample code:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> </dependencies>
Configure Maven plugins.
Specify the organization as
org.springframework.boot, the name asspring-boot-maven-plugin, and the plugin as used to package Spring Boot applications into executable JAR or WAR packages that can be directly run. To avoid conflicts with other plugins or tools, the Lombok dependency is included during the build process.Sample code:
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build>
application.yml
The application.yml file is a configuration file for a Spring Boot application. It contains key configuration items that set the application context path, listening port number, and database connection information and JPA-related properties.
The code in the application.yml file mainly includes the following parts:
Serversectionservlet: used to configure Servlet-related properties.context-path: specifies the application context path astestspringdatajpa.port: specifies the listening port number of the application as 8890.
Code:
server: servlet: context-path: /testspringdatajpa port: 8890Springsectiondatasource: used to configure data source-related properties, that is, database connection information.driver-class-name: specifies the database driver class name ascom.mysql.cj.jdbc.Driver.url: specifies the database connection URL, including the database address, port number, and database name.username: specifies the username for connecting to the database.password: specifies the password for connecting to the database.type: specifies to use the Druid connection pool as the data source.
Code:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://host:port/schema_name?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 username: user_name password: ****** type: com.alibaba.druid.pool.DruidDataSourceJPAsectionhibernate: used to configure Hibernate-related properties.ddl-auto: specifies that Hibernate automatically updates the database structure toupdatewhen it starts.show-sql: specifies whether to print SQL statements in the console, with a value oftrue.format-sql: specifies whether to format the printed SQL statements, with a value oftrue.
open-in-view: specifies whether to enable theOpen-in-Viewmode, with a value offalse.
Code:
jpa: hibernate: ddl-auto: update show-sql: true format-sql: true open-in-view: false
userRepository.java
The userRepository.java file defines methods for database operations on the User entity through a DAO interface. It includes custom update and query methods that use SQL and HQL statements.
The code in the userRepository.java file mainly includes the following parts:
Import other classes and interfaces.
Declare the following interfaces and classes in the current file:
Userclass: used to operate and process user objects in service classes.JpaRepositoryinterface: used to inherit the interface to obtain basic CRUD operation methods.Modifyingannotation: used to mark methods for modification operations.Queryannotation: used to define custom query methods.Paramannotation: used to map method parameters to parameters in query statements.Repositoryannotation: used to mark the DAO interface as a Spring repository component.
Code:
import com.oceanbase.testspringdatajpa.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository;Define the
UserRepositoryinterface.The
UserRepositoryinterface is used to access user data. It is marked as a SpringRepositorycomponent and thebeanname is specified asuserRepository.- Use the
@Queryannotation to specify an SQL statement and setnativeQuery = trueto use native SQL statements. - Use the
@Modifyingannotation to define a custom update method that uses native SQL statements for updates. - Use the
@Queryannotation to specify an HQL (Hibernate Query Language) statement and use the@Paramannotation to map method parameters to parameters in the HQL statement.
Code:
@Repository("userRepository") public interface UserRepository extends JpaRepository<User, Integer> { @Query(value = "update test_springdatajpa_2 set username=?1 where id=?2", nativeQuery = true) @Modifying int updateById(String name, String id); @Query("SELECT u FROM User u WHERE u.username = :username") User findUser(@Param("username") String username); }- Use the
User.java
The User.java file defines the User class to represent a user object.
The code in the User.java file mainly includes the following parts:
Import other classes.
javax.persistence.*: used to import all classes from thejavax.persistencepackage.javax.persistenceis the standard package for Java Persistence API (JPA), providing a set of interfaces and annotations for object-relational mapping (ORM).Code:
import javax.persistence.*;Define the
Userobject. Use JPA annotations to identify the mapping relationships between the entity class and the table, including the table name, primary key, and field name. Use the@Entityannotation to mark the class as an entity class, the@Tableannotation to specify the corresponding database table name, the@Idannotation to mark the primary key of the entity class, the@GeneratedValueannotation to specify the primary key generation strategy, and the@Columnannotation to specify the field name and constraints. The class has two properties,idandusername, which represent the unique identifier and username of the user, respectively. It also provides a default constructor to create an emptyUserobject.Code:
@Entity @Table(name = "test_springdatajpa_2") public class User { @Id @GeneratedValue(strategy = GenerationType.TABLE) @Column(name = "id", nullable = false) private Integer id; @Column(name = "username") private String username; public User() { } }Get and set the
idandnamevalues. The entity class provides a parameterized constructor to create an entity class object and initialize theidandusernameproperties. Define four methods to get and set the values of theidandnameproperties.- The
getIdmethod is used to get theidvalue. - The
setIdmethod is used to set theidvalue. - The
getNamemethod is used to get the usernamenamevalue. - The
setNamemethod is used to set the usernamenamevalue.
Code:
public User(Integer id, String username) { this.id = id; this.username = username; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }- The
Return the string representation of the
Userobject.Override the
toStringmethod in theUserclass to return the string representation of theUserobject. Define@Overrideto override the method with the same name in the parent class. Define thetoStringmethod to return the string representation of theUserobject. Use string concatenation to format the values of theidandnameproperties into a string and return it to the callerUser.Code:
@Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + '}'; }
Introduction to the UserServiceImpl.java file
The UserServiceImpl.java file uses JPA to perform CRUD operations on user data.
The code in the UserServiceImpl.java file mainly includes the following parts:
Import other classes and interfaces.
Declare the following interfaces and classes in the current file:
UserRepositoryclass: used to inject and call methods defined in data access objects (DAOs) in service classes.Userclass: used to operate and process user objects in service classes.UserServiceclass: used to inject and call methods defined in service classes in other classes.Autowiredannotation: used to automatically inject dependency objects.Pageclass: used to encapsulate the results of a paginated query.PageRequestclass: used to create a paginated request object.Pageableinterface: used to define a paginated request interface.Sortclass: used to define a sorting rule.Serviceannotation: used to mark a class as a service class.Transactionalannotation: used to mark a transaction method.Iteratorclass: used to traverse a collection.Optionalclass: used to process objects that may be null.
Sample code:
import com.oceanbase.testspringdatajpa.dao.UserRepository; import com.oceanbase.testspringdatajpa.entity.User; import com.oceanbase.testspringdatajpa.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Iterator; import java.util.Optional;The
UserServiceImplclass implements the methods declared in theUserServiceinterface.The
UserRepositoryclass is used to access the database through dependency injection. The methods for inserting, deleting, updating, and querying user data are implemented. The methods support paginated queries. The@Transactionalannotation is used to enable transaction support and ensure that database operations are performed within a transaction.Define the
UserRepositoryattribute. Define a privateUserRepositoryattribute and use the@Autowiredannotation in the constructor for dependency injection. Inject theUserRepositorydependency through the constructor and use theuserRepositoryattribute to access and operate user data.Sample code:
private final UserRepository userRepository; @Autowired public UserServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; }Insert user data. The
insertUsermethod accepts aUserobject as a parameter. TheUserRepositoryclass'ssavemethod is called to save the user object to the database.Sample code:
@Override public void insertUser(User user) { userRepository.save(user); }Delete user data. The
deleteUsermethod calls theexistsByIdmethod of theUserRepositoryclass to check whether a user with the specified ID exists. If the user exists, the user is deleted. If the user does not exist, the method returns directly.Sample code:
@Override public void deleteUser(Integer id) { if (!userRepository.existsById(id)) { return; } }Modify user data. The
updateUsermethod calls thesavemethod of theUserRepositoryclass to save the user object to the database, thereby performing an update. The method returns the integer value1, indicating that the update was successful. Additionally, the method for updating user data based on the username andidis implemented. TheupdateByIdmethod of theUserRepositoryclass is called to perform the update, and the result of the update is returned.Sample code:
@Override public int updateUser(User user) { userRepository.save(user); return 1; } //update based on name and id @Override public int updateUserById(String name, String id) { return userRepository.updateById(name, id); }Query user data.
- Query user data based on the
ID. TheselectUserByIdmethod calls thefindByIdmethod of theUserRepositoryclass to query user data and encapsulates the result as anOptionalobject. TheorElsemethod of theOptionalclass is then called to obtain the value in theOptionalobject and assign it to theuservariable. Finally, the queried user object is returned. - Query user data based on the username. The
selectUserByNamemethod calls thefindUsermethod of theUserRepositoryclass to query user data based on the username and directly returns the queried user object.
Sample code:
@Override public User selectUserById(Integer id) { Optional<User> optional = userRepository.findById(id); User user = optional.orElse(null); return user; } @Override public User selectUserByName(String username) { return userRepository.findUser(username); }- Query user data based on the
Query all user data in a paginated manner. The
selectUserAllmethod creates aSortobject to specify the sorting rule and creates aPageableobject to specify the paginated parameters. ThefindAllmethod of theUserRepositoryclass is called to query user data, and aPageobject is returned. Theiteratormethod of thePageobject is then called to obtain an iterator for the user data. Finally, the user data iterator is returned.Sample code:
@Override public Iterator<User> selectUserAll(Integer pageNum, Integer pageSize) { Sort sort = Sort.by(Sort.Direction.ASC, "id"); Pageable pageable = PageRequest.of(pageNum, pageSize, sort); Page<User> users = userRepository.findAll(pageable); Iterator<User> userIterator = users.iterator(); return userIterator; }
Introduction to the UserService.java file
The UserService.java file uses JPA to perform CRUD operations on user data.
The code in the UserService.java file mainly includes the following parts:
Import other classes and interfaces.
Declare the following classes in the current file:
Userclass: used to operate and process user objects in service classes.Iteratorclass: used to traverse a collection.
Sample code:
import com.oceanbase.testspringdatajpa.entity.User; import java.util.Iterator;Define the
UserServiceinterface. TheUserServiceinterface defines methods for inserting, deleting, updating, and querying user data. The interface contains the following methods and classes:insertUsermethod: used to insert user data.deleteUsermethod: used to delete user data.updateUsermethod: used to update user data.updateUserByIdmethod: used to modify thenameof a user based on theid.selectUserByIdmethod: used to query user data based on theid.selectUserByNamemethod: used to query user data based on the username.selectUserAllmethod: used to query all user data in a paginated manner.Userclass: used to operate and process user objects in service classes.Iteratorclass: used to traverse a collection.
Sample code:
public interface UserService { void insertUser(User user); void deleteUser(Integer id); int updateUser(User user); int updateUserById(String name, String id); User selectUserById(Integer id); User selectUserByName(String username); Iterator<User> selectUserAll(Integer pageNum, Integer pageSize); }
Introduction to TestSpringDataJpaApplication.java
The TestSpringDataJpaApplication.java file is used to start and configure the Spring Boot application.
The TestSpringDataJpaApplication.java file contains the following code:
Define classes and interfaces. The following classes are declared in this file:
SpringApplicationclass: used to start the Spring Boot application.@SpringBootApplicationannotation: used to mark the entry class of the Spring Boot application.
Sample code:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;Define the
TestSpringDataJpaApplicationclass. Use the@SpringBootApplicationannotation to mark the entry class of the Spring Boot application and call theSpringApplication.runmethod in themainmethod to start the application.Sample code:
@SpringBootApplication public class TestSpringDataJpaApplication { public static void main(String[] args) { SpringApplication.run(TestSpringDataJpaApplication.class, args); } }
Introduction to TestSpringDataJpaApplicationTests.java
The TestSpringDataJpaApplicationTests.java file is used to start and configure the Spring Boot application.
The TestSpringDataJpaApplicationTests.java file contains the following code:
Import other classes and interfaces. The following classes are declared in this file:
Userclass: used to operate and process user objects in the service class.UserServiceclass: used to inject and call methods defined in the service class in other classes.@Testannotation: used to mark test methods.Autowiredannotation: used to automatically inject dependent objects.@SpringBootTestannotation: used to test the Spring Boot application.Iteratorclass: used to traverse a collection.
Sample code:
import com.oceanbase.testspringdatajpa.entity.User; import com.oceanbase.testspringdatajpa.service.UserService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Iterator;Define the
UserServicemethod. This method is used to test the methods of theUserServiceservice in the Spring Boot application. It injects theUserServicedependency and calls each method to test the functionality of inserting, deleting, updating, and querying user data, and prints the related results.Use the
@Autowiredannotation. Automatically inject the implementation class of theUserServiceinterface into theuserServicevariable.Sample code:
@Autowired private UserService userService;Use the
contextLoadsmethod for testing.Insert user data. Use a
forloop to call theinsertUsermethod ofuserServiceto insert 10 user data records.Sample code:
for (int i = 1; i <= 10; i++) { userService.insertUser(new User(i, "insert" + i)); }Delete user data. Call the
deleteUsermethod ofuserServiceto delete user data with id 1.Sample code:
userService.deleteUser(1);Modify user data. Call the
updateUsermethod ofuserServiceto update user data with id 2.Sample code:
userService.updateUser(new User(2, "update"));Query user data.
- Call the
selectUserByIdmethod ofuserServiceto query user data by id and assign the result to theuservariable. Print theuserobject. - Call the
selectUserByNamemethod ofuserServiceto query user data by username and assign the result to theuserByNamevariable. Print theuserByNameobject.
Sample code:
User user = userService.selectUserById(2); System.out.println("user = " + user); User userByName = userService.selectUserByName("insert"); System.out.println("userByName = " + userByName);- Call the
Query user data in pages. Call the
selectUserAllmethod ofuserServiceto query all user data in pages and assign the result to theuserIteratorvariable. Use theforEachRemainingmethod to traverseuserIteratorand print each user object.Sample code:
Iterator<User> userIterator = userService.selectUserAll(0, 5); userIterator.forEachRemaining(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.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.oceanbase</groupId>
<artifactId>java-oceanbase-springdatajpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>java-oceanbase-springdatajpa</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.2</version>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
server:
servlet:
context-path: /testspringdatajpa
port: 8890
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:oceanbase://host:port/schema_name?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: user_name
password: ******
type: com.alibaba.druid.pool.DruidDataSource
jpa:
hibernate:
ddl-auto: update
show-sql: true
format-sql: true
open-in-view: false
package com.oceanbase.testspringdatajpa.dao;
import com.oceanbase.testspringdatajpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository("userRepository")
public interface UserRepository extends JpaRepository<User, Integer> {
//Custom repository handwritten SQL, placeholder value transfer form
@Query(value = "update test_springdatajpa_2 set username=?1 where id=?2", nativeQuery = true)
@Modifying
int updateById(String name, String id);
//SPEL expression, hql syntax
@Query("SELECT u FROM User u WHERE u.username = :username")
User findUser(@Param("username") String username);//Mapping parameter username to database field username
}
package com.oceanbase.testspringdatajpa.entity;
import javax.persistence.*;
@Entity
@Table(name = "test_springdatajpa_2")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "username")
private String username;
public User() {
}
public User(Integer id, String username) {
this.id = id;
this.username = username;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
'}';
}
}
package com.oceanbase.testspringdatajpa.service.impl;
import com.oceanbase.testspringdatajpa.dao.UserRepository;
import com.oceanbase.testspringdatajpa.entity.User;
import com.oceanbase.testspringdatajpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Iterator;
import java.util.Optional;
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Autowired
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
//insert
@Override
public void insertUser(User user) { userRepository.save(user); }
//delete
@Override
public void deleteUser(Integer id) {
if (!userRepository.existsById(id)) {
return;
}
}
//update
@Override
public int updateUser(User user) {
userRepository.save(user);
return 1;
}
//update based on name and id
@Override
public int updateUserById(String name, String id) {
return userRepository.updateById(name, id);
}
// select one user
@Override
public User selectUserById(Integer id) {
Optional<User> optional = userRepository.findById(id);
User user = optional.orElse(null);
return user;
}
//query user based on username
@Override
public User selectUserByName(String username) {
return userRepository.findUser(username);
}
@Override
public Iterator<User> selectUserAll(Integer pageNum, Integer pageSize) {
//By passing parameters to this method, physical pagination can be achieved, which is very simple.
Sort sort = Sort.by(Sort.Direction.ASC, "id");
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Page<User> users = userRepository.findAll(pageable);
Iterator<User> userIterator = users.iterator();
return userIterator;
}
}
package com.oceanbase.testspringdatajpa.service;
import com.oceanbase.testspringdatajpa.entity.User;
import java.util.Iterator;
public interface UserService {
//insert
void insertUser(User user);
//delete
void deleteUser(Integer id);
//update
int updateUser(User user);
//customize SQL and modify name based on id
int updateUserById(String name, String id);
//select one user
User selectUserById(Integer id);
//customize SQL to query users based on username
User selectUserByName(String username);
//query all users
Iterator<User> selectUserAll(Integer pageNum, Integer pageSize);
}
package com.oceanbase.testspringdatajpa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestSpringDataJpaApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringDataJpaApplication.class, args);
}
}
package com.oceanbase.testspringdatajpa;
import com.oceanbase.testspringdatajpa.entity.User;
import com.oceanbase.testspringdatajpa.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Iterator;
@SpringBootTest
class TestSpringDataJpaApplicationTests {
@Autowired
private UserService userService;
@Test
void contextLoads() {
//insert
for (int i = 1; i <= 10; i++) {
userService.insertUser(new User(i, "insert" + i));
}
//delete
userService.deleteUser(1);
//update
userService.updateUser(new User(2, "update"));
//selectUserById
User user = userService.selectUserById(2);
System.out.println("user = " + user);
//selectUserByName
User userByName = userService.selectUserByName("insert");
System.out.println("userByName = " + userByName);
//query all users
Iterator<User> userIterator = userService.selectUserAll(0, 5);
userIterator.forEachRemaining(System.out::println);
}
}
References
For more information about OceanBase Connector/J, see OceanBase JDBC driver.
Download the Java OceanBase SpringDataJPA sample project