SpringDataJPA application that connects to seekdb
This topic describes how to build an application by using the SpringDataJPA framework and seekdb to perform basic operations such as table creation, data insertion, and data query.
Download the java-oceanbase-springdatajpa sample project
Prerequisites
-
You have installed seekdb.
-
You have installed JDK 1.8 and Maven.
-
You have installed IntelliJ IDEA.
infoThe tool used to run the code in this document is IntelliJ IDEA 2021.3.2 (Community Edition). You can also choose a tool of your preference to run the sample code.
Procedure
The following steps are based on the Windows environment. If you are using other operating systems or compilers, the steps may vary.
- Obtain the connection string of seekdb.
- 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 seekdb connection string
-
Contact the deployment personnel or administrator of seekdb to obtain the corresponding database connection string.
mysql -hxx.xx.xx.xx -P2881 -uroot -p**** -A -
Fill in the URL information based on the deployed seekdb.
infoThe 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 IP address for connecting to seekdb. Replace it with the actual IP address. You can also use the local IP address or 127.0.0.1. -
port: the port for connecting to seekdb. Replace it with the actual port. The default value is 2881, which can be customized during the deployment of seekdb. -
schema_name: the name of the schema to be accessed. -
user_name: the username, specified by the-uparameter. The default username isroot. -
password: the account password. -
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 select File > Open....

-
In the Open File or Project window that appears, select the project file and click OK to complete the import.
-
IntelliJ IDEA will automatically identify various types of files in the project and display the project's directory structure, file list, module list, and dependencies in the Project tool window. The Project tool window is usually located on the far left of the IntelliJ IDEA interface and is typically open by default. If it is closed, you can click View > Tool Windows > Project in the menu bar or use the shortcut key Alt + 1 to reopen it.
infoWhen importing a project using IntelliJ IDEA, it will automatically detect the pom.xml file in the project and download the required dependency libraries based on the described dependencies in the file, then add 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 seekdb Connection String.
Example:
- The name of the database driver is:
com.mysql.cj.jdbc.Driver - The IP address of seekdb is
10.10.10.1. - The access port is 2881.
- The name of the schema to be accessed is
test. - The connection account is
root. - The password is
******.
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
password: ******
type: com.alibaba.druid.pool.DruidDataSource
Step 4: Run the java-oceanbase-springdatajpa project
Run path
- In the project structure, locate the
TestSpringDataJpaApplicationTests.javafile in src > test > java. - In the tool menu bar, select Run > Run... > TestSpringDataJpaApplicationTests.contextLoads, or click the green triangle in the upper right corner to run.
- View the project's log information 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'}
FAQs
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
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 SSL connections with seekdb, add the following parameter to the JDBC URL:
jdbc:mysql://host:port/database?useSSL=true&requireSSL=true
4. Special characters in the account 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");
When using MySQL Connector/J 8.x, ensure that the account or password does not contain a number sign (#). Otherwise, you may encounter a connection error.
Project code
Click java-oceanbase-springdatajpa to download the project code. The code is in a compressed file named java-oceanbase-springdatajpa.
After decompressing the file, 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. It contains information about the project's dependencies, plugins, and build settings..idea: a directory used by the IDE (Integrated Development Environment) to store project-related configuration information.src: a directory typically used to store the source code of the project.main: a directory for storing the main source code and resource files.java: a directory for storing 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. It contains all the Java classes of the project.TestSpringDataJpaApplication.java: the entry class of the Spring Boot application.dao: a directory for storing the Data Access Object (DAO) packages, which are used to access 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 for storing entity classes that correspond to database tables.User.java: the user persistence object, which is used to map the fields of the user data table.service: a directory for storing service interface files that define business logic interfaces.UserService.java: the user service interface, which defines the methods for operating on user data.impl: a directory for storing the implementation files of 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 of Spring Data JPA.target: a directory for storing compiled Class files and Jar packages.
Introduction to the pom.xml file
If you just want to verify the example, you can use the default code without any modifications. You can also modify the pom.xml file according to your needs based on the following instructions.
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.Code:
<?xml version="1.0" encoding="UTF-8"?> -
Configure the namespace and model version of the POM.
- Use
xmlnsto set the POM namespace tohttp://maven.apache.org/POM/4.0.0. - Use
xmlns:xsito set the XML namespace tohttp://www.w3.org/2001/XMLSchema-instance. - Use
xsi:schemaLocationto set the POM namespace tohttp://maven.apache.org/POM/4.0.0and the location of the POM XSD file tohttps://maven.apache.org/xsd/maven-4.0.0.xsd. - Use the
<modelVersion>element to set the POM model version used by the POM file to4.0.0.
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 set the parent project identifier toorg.springframework.boot. - Use
<artifactId>to set the parent project dependency tospring-boot-starter-parent. - Use
<version>to set the parent project version to2.7.0. - Use
relativePathto indicate that the parent project path is empty.
Code:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent> - Use
-
Configure basic information.
- Use
<groupId>to set the project identifier tocom.oceanbase. - Use
<artifactId>to set the project dependency tojava-oceanbase-springdatajpa. - Use
<version>to set the project version to0.0.1-SNAPSHOT. - Use
descriptionto introduce the project information asDemo project for Spring Boot.
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.
Set the Java version used by the project to 1.8.
Code:
<properties>
<java.version>1.8</java.version>
</properties> -
Configure core dependencies.
-
Set the organization of the dependency to
org.springframework.boot, the name tospring-boot-starter-data-jpa, and the dependency library to include the necessary dependencies and configurations for data access using JPA. Spring Boot Starter Data JPA is a Spring Boot starter.Code:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> -
Set the organization of the dependency to
org.springframework.boot, the name tospring-boot-starter-web, and the dependency library to include the necessary dependencies and configurations for web development using Spring Boot. It is a Spring Boot starter.Code:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> -
Set the organization of the dependency to
org.springframework.boot, the name tospring-boot-starter-test, and the scope totest. This dependency allows you to use the testing framework and tools provided by Spring Boot, such as JUnit, Mockito, and Hamcrest.Code:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> -
Set the organization of the dependency to
com.alibaba, the name todruid, and the version to1.2.8. This dependency allows you to use the Druid library for managing and optimizing database connection acquisition and release.Code:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency> -
Set the organization of the dependency to
com.oceanbase, the name tooceanbase-client, and the version to2.4.2. This dependency allows you to use the client features provided by seekdb, such as connection, query, and transaction.Code:
<dependencies>
<dependency>
<groupId>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
-
-
Configure Maven plugins.
Set the organization of the dependency to
org.springframework.boot, the name tospring-boot-maven-plugin, and the plugin to be used for packaging Spring Boot applications into executable JAR or WAR packages. This plugin allows you to directly run the applications. To avoid conflicts with other plugins or tools, the Lombok dependency is included during the build process.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, including the application context path, listening port number, and database connection information and JPA-related attributes.
The application.yml file contains the following code:
-
Serversectionservlet: used to configure Servlet-related attributes.context-path: specifies the application context path astestspringdatajpa.port: specifies the listening port number as 8890.
Sample code:
server:
servlet:
context-path: /testspringdatajpa
port: 8890 -
Springsection-
datasource: used to configure data source-related attributes, 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 the use of the Druid connection pool as the data source.
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.DruidDataSource -
JPAsectionhibernate: used to configure Hibernate-related attributes.ddl-auto: specifies the database structure update mode asupdatewhen Hibernate starts.show-sql: specifies whether to print SQL statements in the console, with the valuetrue.format-sql: specifies whether to format the printed SQL statements, with the valuetrue.
open-in-view: specifies whether to enable theOpen-in-Viewmode, with the valuefalse.
Sample 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 userRepository.java file contains the following code:
-
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 DAO interfaces as Spring repository components.
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. 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 customize an update method and perform an update operation using native SQL statements. - 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.
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
User.java
The User.java file defines the User class to represent a user object.
The User.java file contains the following code:
-
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).Sample 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 for creating an emptyUserobject.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 parameterized constructor for creating an entity class object and initializing theidandusernameproperties. Define four methods for getting and setting theidandnameproperty values.- 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.
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 the string representation of the
Userobject.Override the
toStringmethod in theUserclass to return the string representation of theUserobject. Define@Overrideto override the same-named method in the parent class. Define thetoStringmethod to return the string representation of theUserobject. Concatenate strings to format theidandnameproperty values into a string and return it to the callerUser.Sample 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 database operations for user data.
The code in the UserServiceImpl.java file mainly includes the following parts:
-
Import other classes and interfaces.
Declare the interfaces and classes included in the current file:
UserRepositoryclass: used to inject and call methods defined in the data access object (DAO) in the service class.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.Autowiredannotation: used to automatically inject dependency objects.Pageclass: used to encapsulate the results of a query.PageRequestclass: used to create a pagination request object.Pageableinterface: used to define the pagination request interface.Sortclass: used to define the sorting rules.Serviceannotation: used to mark a class as a service class.Transactionalannotation: used to mark transaction methods.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.Access the database by using dependency injection of the
UserRepositoryclass. The methods for inserting, deleting, updating, and querying user data are implemented. Pagination queries are supported. The@Transactionalannotation is used to enable transaction support, ensuring that database operations are executed in a transaction.-
Define the
UserRepositoryattribute. Define a privateUserRepositoryattribute and use the@Autowiredannotation in the constructor for dependency injection. Inject theUserRepositorydependency by using 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 determine whether a user with the specified ID exists. If the user exists, the user is deleted. Otherwise, the method returns directly.Sample code:
@Override
public void deleteUser(Integer id) {
if (!userRepository.existsById(id)) {
return;
}
} -
Update user data. The
updateUsermethod calls thesavemethod of theUserRepositoryclass to save the user object to the database, thereby performing an update operation. The method returns the integer value1, indicating that the update operation is successful. Additionally, the method for updating user data based on the username andidis implemented by calling theupdateByIdmethod of theUserRepositoryclass. The update result 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 theOptionalobject is then called to obtain the value in theOptionalobject and assign it to theuservariable. Finally, the 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 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 pages. The
selectUserAllmethod creates aSortobject to specify the sorting rules, creates aPageableobject to specify the pagination parameters, and calls thefindAllmethod of theUserRepositoryclass to query user data. APageobject is returned. Theiteratormethod of thePageobject is then called to obtain an iterator for 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 database operations for user data.
The code in the UserService.java file mainly includes the following parts:
-
Import other classes and interfaces.
Declare the classes included in the current file:
Userclass: used to operate and process user objects in the service class.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 includes 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 pages. -
Userclass: used to operate and process user objects in the service class. -
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 a Spring Boot application.
The code in the TestSpringDataJpaApplication.java file mainly includes the following parts:
-
Define classes and interfaces. Declare the following classes in the current file:
SpringApplicationclass, which is used to start a Spring Boot application.@SpringBootApplicationannotation, which is used to mark the entry class of a 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 a 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 a Spring Boot application.
The code in the TestSpringDataJpaApplicationTests.java file mainly includes the following parts:
-
Import other classes and interfaces. Declare the following classes in the current file:
Userclass, which is used to operate and process user objects in service classes.UserServiceclass, which is used to inject and call methods defined in service classes in other classes.@Testannotation, which is used to mark test methods.Autowiredannotation, which is used to automatically inject dependent objects.@SpringBootTestannotation, which is used to test Spring Boot applications.Iteratorclass, which is 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 a Spring Boot application. It injects theUserServicedependency, calls each method to test the insertion, deletion, update, and query of 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 by page. Call the
selectUserAllmethod ofuserServiceto query all user data by page 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
tab pom.xml
<?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>
tab application.yml
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
tab userRepository.java
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
}
tab User.java
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 + '\'' +
'}';
}
}
tab UserServiceImpl.java
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;
}
}
tab UserService.java
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);
}
tab TestSpringDataJpaApplication.java
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);
}
}
tab TestSpringDataJpaApplicationTests.java
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.