Home >Java >javaTutorial >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 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.
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.
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
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方法 }
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
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.
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!