This topic describes how to build an application using the Spring Data JPA framework and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, and data query.
Prerequisites
- You have installed OceanBase Database.
- You have installed Java Development Kit (JDK) 1.8 and Maven.
- You have installed IntelliJ IDEA.
Note
In this topic, IntelliJ IDEA Community Edition 2021.3.2 is used to run the sample code. You can also choose a suitable tool as needed.
Procedure
Note
The following procedure applies to Windows. If you use another operating system or compiler, the procedure can be slightly different.
- Obtain the OceanBase Database connection string.
- Import the
java-oceanbase-springdatajpaproject to IntelliJ IDEA - Modify the database connection information in the
java-oceanbase-springdatajpaproject. - Run the
java-oceanbase-springdatajpaproject.
Step 1: Obtain the OceanBase Database connection string
Contact the deployment personnel or administrator of OceanBase Database to obtain the connection string.
obclient -hxx.xx.xx.xx -P2883 -uroot@sys#cluster -p**** -AEnter the URL of OceanBase Database.
Note
The URL of OceanBase Database is required in the
application.ymlfile.jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$password&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8The parameters are described as follows:
host: the IP address for connecting to OceanBase Database, which is the IP address of OceanBase Database Proxy (ODP) for connection through ODP, or the IP address of an OBServer node for direct connection.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 of the account in the format of user@tenant#cluster name or username@SERVICE:service name, which is specified by the-uparameter. When the value is in the user@tenant#cluster name format, the default tenant issysand the default administrator isroot. The cluster name is not required when you directly connect to OceanBase Database, but is required when you connect to OceanBase Database through ODP.password: the password of the account.characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8: the additional connection properties.characterEncoding: the character encoding format for the URL of OceanBase Database. The default value isutf8.useSSL: specifies whether to useSSL/TLSduring forced connections. The default value isfalse.serverTimezone: the server time zone. The default value is China Standard Time (CST).
For more information about URL parameters, see Database URL.
Step 2: Import the java-oceanbase-springdatajpa project to 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 identifies various files in the project. You can view project information such as the directory structure, file list, module list, and dependencies in the Project window. Generally, the Project window is at the leftmost of the UI of IntelliJ IDEA and is opened by default. If the Project window is closed, you can choose View > Tool Windows > Project in the menu bar or press Alt + 1 to open it.
Note
When you use IntelliJ IDEA to import a project, IntelliJ IDEA automatically detects the `pom.xml` file in the project, downloads the required dependency libraries based on the dependencies described in the file, and adds them to the project.
View the project.

Step 3: Modify the database connection information in the java-oceanbase-springdatajpa project
Modify the database connection string in the application.yml file based on the information obtained in Step 1: Obtain the OceanBase Database connection string.
Here is a connection information 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 access port is 2881.
- The name of the schema to be accessed is
test. - The tenant account is
root@mysql001.mysql001is a MySQL user tenant created in OceanBase Database, androotis the username of a user in themysql001tenant. - The password is
******.
Here is the sample code:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://10.10.10.1:2881/test?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: root@mysql001
password: ******
type: com.alibaba.druid.pool.DruidDataSource
Step 4: Run the java-oceanbase-springdatajpa project
Path
- Find the
TestSpringDataJpaApplicationTests.javafile under src > test > java in the project package. - Choose Run > Run... > TestSpringDataJpaApplicationTests.contextLoads in the menu bar or click the green triangle in the upper-right corner to run the file.
- View the logs and output of the project in the Console window of IDEA.
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'}
Project code
Click here to download the project code, which is a package named java-oceanbase-springdatajpa.
Decompress the package to obtain 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
The files and directories are described as follows:
pom.xml: the configuration file of the Maven project, which contains the dependencies, plug-ins, and build rules of the project..idea: a directory used in an Integrated Development Environment (IDE) to store configuration information related to the project.src: a directory that stores the source code in 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 of the Java package.oceanbase: the root directory of the project.testspringdatajpa: the root directory of the Java package, which contains all the Java classes of the project.TestSpringDataJpaApplication.java: the entry class for the Spring Boot application.dao: stores the data access object (DAO) package for accessing databases or other data storage services.UserRepository.java: the user data access interface, which defines the create, read, update, and delete (CRUD) operations on user data.entity: the entity class directory, which stores the Java classes corresponding to the database tables.User.java: the user persistent object that is mapped to fields in a user data table.service: the service interface directory, which defines business logic interfaces.UserService.java: the user service interface, which defines operations on user data.impl: the service implementation directory, which stores the implementation classes of business logic.UserServiceImpl.java: the user service implementation class, which implements the methods defined in theUserServiceinterface.resources: a directory that stores resource files, such as configuration files and SQL files.application.yml: the configuration file of the application, which is used to configure information such as database connection information.static: stores static files, such as CSS and JavaScript files.templates: stores template files, such as HTML templates.test: a directory that stores the test code and resource files.TestSpringDataJpaApplicationTests.java: stores classes that implement and verify features related to Spring Data JPA.target: a directory that stores compiled class files and JAR packages.
Code in pom.xml
Note
You can retain the default code in this file for verification purposes or modify the code in the file as needed.
Perform the following steps to configure the pom.xml file:
Declare the file.
Declare the file to be an XML file that uses the XML standard 1.0 and character encoding format UTF-8.
Here is the sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure namespaces and the POM model version.
xmlns: the default XML namespace for the POM, which is set tohttp://maven.apache.org/POM/4.0.0.xmlns:xsi: the XML namespace for XML elements prefixed withxsi, which is set tohttp://www.w3.org/2001/XMLSchema-instance.xsi:schemaLocation: the location of an XML schema definition (XSD) file. The value consists of two parts: the default XML namespace (http://maven.apache.org/POM/4.0.0) and the URI of the XSD file (https://maven.apache.org/xsd/maven-4.0.0.xsd).<modelVersion>: the POM model version used by the POM file, which is set to4.0.0.
Here is the 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>Configure parent project information.
<groupId>: the ID of the parent project group, which is set toorg.springframework.boot.<artifactId>: the name of the parent project, which is set tospring-boot-starter-parent.<version>: the version of the parent project, which is set to2.7.0.<relativePath>: an empty path for the parent project.
Here is the sample code:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.0</version> <relativePath/> </parent>Configure basic information.
<groupId>: the ID of the project group, which is set tocom.oceanbase.<artifactId>: the name of the project, which is set tojava-oceanbase-springdatajpa.<version>: the version of the project, which is set to0.0.1-SNAPSHOT.<description>: the project information, which is set toDemo project for Spring Boot.
Here is the 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>Configure the Java version.
Specify to use Java 1.8 for the project.
Here is the sample code:
<properties> <java.version>1.8</java.version> </properties>Configure core dependencies.
Define a dependency named
spring-boot-starter-data-jpathat belongs to theorg.springframework.bootgroup. This dependency contains necessary dependencies and configurations for JPA-based data accesses, and is a Spring Boot starter.Here is the sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>Define a dependency named
spring-boot-starter-webthat belongs to theorg.springframework.bootgroup. This dependency contains necessary dependencies and configurations for Spring Boot-based web development, and is a Spring Boot starter.Here is the sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>Define a dependency named
spring-boot-starter-testthat belongs to theorg.springframework.bootgroup. This dependency takes effect in thetestscope and provides test frameworks and tools of Spring Boot, such as JUnit, Mockito, and Hamcrest.Here is the sample code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>Define a dependency named
druidthat belongs to thecom.alibabagroup and whose version is1.2.8. This dependency allows the project to use the Druid library to manage and optimize the acquisition and release of database connections.Here is the sample code:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency>Define a dependency named
oceanbase-clientthat belongs to thecom.oceanbasegroup and whose version is2.4.2. With this dependency, you can use the features of OceanBase Command-Line Client (OBClient), such as connections, queries, and transactions.Here is the sample code:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> </dependencies>
Configure the Maven plug-in.
Define a plug-in named
spring-boot-maven-pluginthat belongs to theorg.springframework.bootgroup. This plug-in can be used to package Spring Boot applications as executable JAR packages or WAR packages, or directly run Spring Boot applications. To avoid conflicts with other plug-ins or tools, exclude thelombokdependency during building.Here is the 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>
Code in application.yml
The application.yml file is the configuration file of the Spring Boot application, which contains some key parameters. The file configures the context path and listening port number of the application, database connection information, and JPA-related properties.
Code in the application.yml file contains the following parts:
Serverpartservlet: the servlet properties.context-path: the context path of the application, which is set totestspringdatajpa.port: the listening port number of the application, which is set to8890.
Here is the sample code:
server: servlet: context-path: /testspringdatajpa port: 8890Springpartdatasource: the data source properties, that is, the database connection information.driver-class-name: the class name of the database driver, which is set tocom.mysql.cj.jdbc.Driver.url: the connection URL of the database, which consists of the IP address, port number, and name of the database.username: the username for connecting to the database.password: the password for connecting to the database.type: specifies to use the Druid connection pool as the data source.
Here is the sample 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.DruidDataSourceJPAparthibernate: the Hibernate-related properties.ddl-auto: the operation performed by Hibernate. The valueupdatehere specifies that Hibernate automatically updates the database schema when the application starts.show-sql: specifies whether to print SQL statements to the console. The value istrue.format-sql: specifies whether to format the printed SQL statements. The value istrue.
open-in-view: specifies whether to enable theOpen-in-Viewmode. The value isfalse.
Here is the sample code:
jpa: hibernate: ddl-auto: update show-sql: true format-sql: true open-in-view: false
Code in UserRepository.java
The userRepository.java file defines a DAO interface that contains methods of performing database operations on the User entity. The file contains custom update and query operation methods that use SQL statements and Hibernate Query Language (HQL) statements.
Perform the following steps to configure the userRepository.java file:
Reference other classes and interfaces.
Declare this file to contain the following interfaces and classes:
Userclass: operates and processes user objects in the service class.JpaRepositoryinterface: provides basic CRUD operation methods for interfaces that inherit it.Modifyingannotation: marks modification operation methods.Queryannotation: defines custom query methods.Paramannotation: maps method parameters to parameters in query statements.Repositoryannotation: marks a DAO interface as a Spring repository.
Here is the sample 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. Mark theUserRepositoryinterface as a Spring repository and specifyuserRepositoryas the bean name.- Use the
@Queryannotation withnativeQuery = trueto specify a native SQL statement. - Use the
@Modifyingannotation to mark a custom method that uses a native SQL statement for update. - Use the
@Queryannotation to specify an HQL statement, and use the@Paramannotation to map method parameters to parameters in the HQL statement.
Here is the sample 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
Code in User.java
The User.java file defines the User class to represent user objects.
Perform the following steps to configure the User.java file:
Import other classes.
javax.persistence.*: specifies to import all classes in thejavax.persistencepackage.javax.persistenceis a standard JPA package that provides a set of interfaces and annotations for object-relational mapping (ORM).Here is the sample code:
import javax.persistence.*;Define the
Userobject. Use JPA annotations to map an entity class to a table, including the table name, primary key, and field names. Use the@Entityannotation to mark a class as an entity class. Use the@Tableannotation to specify the name of the mapped-to table. Use the@Idannotation to mark the primary key of the entity class. Use the@GeneratedValueannotation to specify the primary key generation strategy. Use the@Columnannotation to specify field names and constraints. The class has two attributes:idandusername, which represent the unique identifier and name of a user, respectively. The class also provides a default constructor for creating an emptyUserobject.Here is the sample 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 constructor with parameters for creating entity class objects and initializing theidandusernameattributes. Define four methods to get and set the values of theidandnameattributes.- The
getIdmethod gets theidvalue. - The
setIdmethod sets theidvalue. - The
getNamemethod gets thenamevalue. - The
setNamemethod sets thenamevalue.
Here is the sample 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 a string that represents the
Userobject.Override the
toStringmethod in theUserclass to return a string that represents theUserobject. Use the@Overrideannotation to override the method of the same name in the parent class. Define thetoStringmethod that returns a string representation of theUserobject. Concatenate theidandnamevalues to generate a string and return it to the caller.Here is the sample code:
@Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + '}'; }
Code in UserServiceImpl.java
The UserServiceImpl.java file defines the CRUD operations on user data in the database by using JPA.
Perform the following steps to configure the UserServiceImpl.java file:
Reference other classes and interfaces.
Declare this file to contain the following interfaces and classes:
UserRepositoryclass: injects the methods defined in the DAO to the service class and calls these methods.Userclass: operates and processes user objects in the service class.UserServiceclass: injects methods defined in the service class to other classes and calls these methods.Autowiredannotation: automatically injects dependent objects.Pageclass: encapsulates results of pagination queries.PageRequestclass: creates pagination request objects.Pageableinterface: defines pagination requests.Sortclass: defines sorting rules.Serviceannotation: marks a class as a service class.Transactionalannotation: marks a class as transactional.Iteratorclass: traverses a set.Optionalclass: processes objects that may be empty.
Here is the 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;Use the
UserServiceImplclass to implement the methods declared in theUserServiceinterface.Inject the
UserRepositorydependency to implement access to the database. Specifically, implement the methods to insert, delete, update, and query user data, with pagination queries supported. Use the@Transactionalannotation to enable transaction support, which ensures that database operations are performed in transactions.Construct a
UserRepositoryattribute. Define a private attribute nameduserRepositoryand use the@Autowiredannotation on the constructor to inject theUserRepositorydependency, so that theuserRepositoryattribute can be used to access and operate user data.Here is the sample code:
private final UserRepository userRepository; @Autowired public UserServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; }Insert user data. In the
insertUsermethod, accept aUserobject as a parameter and save the object to the database by calling thesavemethod ofUserRepository.Here is the sample code:
@Override public void insertUser(User user) { userRepository.save(user); }Delete user data. In the
deleteUsermethod, call theexistsByIdmethod ofUserRepositoryto check whether the user with the specified ID exists. If the user exists, the method deletes the user. If the user does not exist, the method exits.Here is the sample code:
@Override public void deleteUser(Integer id) { if (!userRepository.existsById(id)) { return; } }Modify user data. In the
updateUsermethod, call thesavemethod ofUserRepositoryto save the updates of a user object to the database. Then, return1to indicate that the user object is updated. In addition, define a method that updates user data based on the name and ID of a user by calling theupdateByIdmethod ofUserRepository, and return the operation result.Here is the 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 by ID. In the
selectUserByIdmethod, call thefindByIdmethod ofUserRepositoryto query data and encapsulate the result as anOptionalobject. Then, call theorElsemethod ofOptionalto get the value in theOptionalobject and assign it to theuservariable. Finally, return the queried user object. - Query user data by username. In the
selectUserByNamemethod, call thefindUsermethod ofUserRepositoryto query user data by username, and directly return the queried user object.
Here is the 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 by ID. In the
Query all user data with pagination. In the
selectUserAllmethod, create aSortobject to specify sorting rules, create aPageableobject to specify the pagination parameters, call thefindAllmethod ofUserRepositoryto query user data, and return aPageobject. Then, get a user data iterator by calling theiteratormethod of thePageobject. Finally, return the user data iterator.Here is the 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; }
Code in UserService.java
The UserService.java file defines the CRUD operations on user data in the database by using JPA.
Perform the following steps to configure the UserService.java file:
Reference other classes and interfaces.
Declare that the current file contains the following classes:
Userclass: operates and processes user objects in the service class.Iteratorclass: traverses a set.
Here is the sample code:
import com.oceanbase.testspringdatajpa.entity.User; import java.util.Iterator;Define the
UserServiceinterface. Define methods in theUserServiceinterface to insert, delete, update, and query user data. The interface contains the following methods and classes:insertUsermethod: inserts user data.deleteUsermethod: deletes user data.updateUsermethod: updates user data.updateUserByIdmethod: modifies thenamevalue for a user of the specified ID.selectUserByIdmethod: queries user data by ID.selectUserByNamemethod: queries user data by username.selectUserAllmethod: queries all user data with pagination.Userclass: operates and processes user objects in the service class.Iteratorclass: traverses a set.
Here is the 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); }
Code in TestSpringDataJpaApplication.java
The TestSpringDataJpaApplication.java file is used to launch and configure a Spring Boot application.
Perform the following steps to configure the TestSpringDataJpaApplication.java file:
Define classes and interfaces. Declare that the current file contains the following classes:
SpringApplicationclass: launches a Spring Boot application.@SpringBootApplicationannotation: marks a class as the entry class of the Spring Boot application.
Here is the sample code:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;Define the
TestSpringDataJpaApplicationclass. Use the@SpringBootApplicationannotation to mark this class as the entry class of a Spring Boot application, and call theSpringApplication.runmethod in themainmethod to launch the application.Here is the sample code:
@SpringBootApplication public class TestSpringDataJpaApplication { public static void main(String[] args) { SpringApplication.run(TestSpringDataJpaApplication.class, args); } }
Code in TestSpringDataJpaApplicationTests.java
The TestSpringDataJpaApplicationTests.java file is used to launch and configure a Spring Boot application.
Perform the following steps to configure the TestSpringDataJpaApplicationTests.java file:
Reference other classes and interfaces. Declare that the current file contains the following classes:
Userclass: operates and processes user objects in the service class.UserServiceclass: injects methods defined in the service class to other classes and calls these methods.@Testannotation: marks a test method.Autowiredannotation: automatically injects dependencies.@SpringBootTestannotation: marks a test class for a Spring Boot application.Iteratorclass: traverses a set.
Here is the 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 tests various methods in theUserServiceservice of the Spring Boot application. The method injects theUserServicedependency to call various methods to test the user data insert, delete, update, and query operations, and prints results.Use the
@Autowiredannotation to automatically inject the implementation class of theUserServiceinterface to theuserServicevariable.Here is the sample code:
@Autowired private UserService userService;Use the
contextLoadsmethod for testing.Insert user data. Use the
forloop and call theinsertUsermethod ofuserServiceto insert 10 user data records.Here is the sample code:
for (int i = 1; i <= 10; i++) { userService.insertUser(new User(i, "insert" + i)); }Delete user data. Call the
deleteUsermethod ofuserServiceto delete the data of the user with the ID1.Here is the sample code:
userService.deleteUser(1);Modify user data. Call the
updateUsermethod ofuserServiceto update the data of the user with the ID2.Here is the 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 user name, and assign the result to theuserByNamevariable. Print theuserByNameobject.
Here is the 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 with pagination. Call the
selectUserAllmethod ofuserServiceto query all user data with pagination, and assign the results to theuserIteratorvariable. Use theforEachRemainingmethod to traverse theuserIteratorvariable and print each user object.Here is the 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 Connector/J.
Download the java-oceanbase-springdatajpa sample project