Using MyBatis to implement data access and persistence in Spring Boot
Spring Boot is a rapid development framework that can help developers quickly build WEB applications. MyBatis is an excellent ORM framework that can simplify data access and persistence between Java and databases. This article will introduce how to use MyBatis to implement data access and persistence in Spring Boot.
1. Spring Boot integrates MyBatis
- Add dependencies
Add MyBatis and MySQL dependencies in the pom.xml file:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency>
Here we use mybatis-spring-boot-starter to integrate MyBatis.
- Configure the data source
Add the database connection properties in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driverClassName=com.mysql.jdbc.Driver
Here we use the MySQL database and connect using the root account, The password is 123456.
- Configuring MyBatis
Spring Boot will automatically scan the mapper path by default. We only need to configure the mapper path in application.properties:
mybatis.mapper-locations=classpath:mapper/*.xml
This configuration indicates that the mapper file is in the mapper folder under the project's classpath.
After completing the above configuration, Spring Boot has completed the integration of MyBatis.
2. Writing entity classes and Mapper
- Writing entity classes
Define a User class to represent a user table in the database:
public class User { private Long id; private String name; private Integer age; // 省略getter和setter方法 }
- Writing Mapper
Define a UserMapper interface to define the addition, deletion, modification and query operations of the User table:
public interface UserMapper { void saveUser(User user); void updateUser(User user); void deleteUser(Long id); User findUserById(Long id); List<User> findAllUsers(); }
Here we define the addition, deletion, modification and query as well as Method to query all users.
3. Write Mapper.xml
Next, we need to write the UserMapper.xml file to implement the operations defined in UserMapper:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.demo.mapper.UserMapper"> <insert id="saveUser" parameterType="com.example.demo.entity.User"> insert into user(name, age) values (#{name}, #{age}) </insert> <update id="updateUser" parameterType="com.example.demo.entity.User"> update user set name = #{name}, age = #{age} where id = #{id} </update> <delete id="deleteUser" parameterType="java.lang.Long"> delete from user where id = #{id} </delete> <select id="findUserById" parameterType="java.lang.Long" resultType="com.example.demo.entity.User"> select * from user where id = #{id} </select> <select id="findAllUsers" resultType="com.example.demo.entity.User"> select * from user </select> </mapper>
In this file, we implement All methods defined in UserMapper, where parameterType represents the parameter type and resultType represents the return value type.
4. Writing Service classes and controllers
- Writing Service classes
Define a UserService class to encapsulate operations on the User table:
@Service public class UserService { @Autowired private UserMapper userMapper; public void saveUser(User user) { userMapper.saveUser(user); } public void updateUser(User user) { userMapper.updateUser(user); } public void deleteUser(Long id) { userMapper.deleteUser(id); } public User findUserById(Long id) { return userMapper.findUserById(id); } public List<User> findAllUsers() { return userMapper.findAllUsers(); } }
In this class, we use the @Autowired annotation to inject UserMapper, that is, you can use the methods defined in UserMapper.
- Writing Controller
Define a UserController class to implement addition, deletion, modification and query operations for users:
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/") public String saveUser(@RequestBody User user) { userService.saveUser(user); return "success"; } @PutMapping("/") public String updateUser(@RequestBody User user) { userService.updateUser(user); return "success"; } @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { userService.deleteUser(id); return "success"; } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.findUserById(id); } @GetMapping("/") public List<User> findAllUsers() { return userService.findAllUsers(); } }
In this class, we use @ The RestController annotation indicates that the current class is a controller, and the access path is specified using the @RequestMapping annotation. At the same time, UserService is injected using the @Autowired annotation, that is, the methods defined in UserService can be used.
5. Test
Now, we have completed the construction and coding of the entire project. Next, we can use tools such as Postman to test the API defined in the controller.
Use POST request to save user information, the request body is:
{ "name": "张三", "age": 18 }
Use PUT request to update user information, the request body is:
{ "id": 1, "name": "李四", "age": 20 }
Use DELETE request to delete the user Information, the URL is:
http://localhost:8080/user/1
Use GET request to obtain user information, the URL is:
http://localhost:8080/user/1
Use GET request to obtain all user information, the URL is:
http://localhost:8080/user/
Six , Summary
This article introduces how to use MyBatis to implement data access and persistence in Spring Boot, and uses a simple example to illustrate the entire process. MyBatis can make Java programs' database operations more efficient and concise. If you need to implement database operations in Spring Boot, you can consider using MyBatis.
The above is the detailed content of Using MyBatis to implement data access and persistence in Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
