1. Basic introduction
1.1 MyBatis
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information to map interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
1.2 Advantages of Spring Boot Integration MyBatis
Integrating Spring Boot and MyBatis can give full play to the rapid development features of Spring Boot and the flexible database operation capabilities of MyBatis. Through this integration, a stable and efficient database access layer can be quickly built, simplified development process and improved development efficiency.
2. Integration steps
2.1 Creating a Spring Boot Project
You can use Spring Initializr(/) to quickly create a Spring Boot project. When creating a project, you need to select the following dependencies:
- Spring Web
- Spring Data JPA
- MySQL Driver
- MyBatis Framework
2.2 Configuring the data source
existConfigure database connection information in the file:
=jdbc:mysql://localhost:3306/yourdatabase =yourusername =yourpassword -class-name=
2.3 Configuring MyBatis
existConfigure the relevant properties of MyBatis in the file:
-locations=classpath:/mapper/*.xml -aliases-package=
-locations configures the location of the MyBatis mapping file, and -aliases-package configures the package name of the entity class, so that the entity class name can be used directly in the MyBatis mapping file without writing a fully qualified name.
2.4 Creating an entity class
Create a Java entity class that maps records in database tables. For example, create a User entity class:
package ; public class User { private Long id; private String username; private String password; // Omit getters and setters}
2.5 Creating a Mapper Interface
Create a Mapper interface that defines the database operation method. For example, create aUserMapper
Interface:
package ; import ; import ; import ; import ; @Mapper public interface UserMapper { @Select("SELECT * FROM user") List<User> findAll(); }
@Mapper
Annotation is used to mark this interface as the Mapper interface of MyBatis.
2.6 Creating a Mapper Mapping File
existresources/mapper
Create a directoryFile, used to implement methods in the Mapper interface:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/"> <mapper namespace=""> <select resultType=""> SELECT * FROM user </select> </mapper>
The namespace attribute specifies the fully qualified name of the Mapper interface, the id attribute specifies the method name to be implemented, and the resultType attribute specifies the type of the result returned.
2.7 Creating a Service Layer
Creates a Service layer that calls methods in the Mapper interface. For example, create a UserService interface and its implementation class UserServiceImpl:
package ; import ; import ; public interface UserService { List<User> findAll(); }
package ; import ; import ; import ; import ; import ; import ; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return (); } }
2.8 Create Controller Layer
Creates a Controller layer that handles client requests. For example, create aUserController
:
package ; import ; import ; import ; import ; import ; import ; import ; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> findAll() { return (); } }
3. Sample complete code
1. Create
existsrc/main/resources
Created in the directorydocument.
2. Configure the data source and MyBatis
Will the originalThe configuration content in is converted to YAML format, as follows:
spring: datasource: url: jdbc:mysql://localhost:3306/yourdatabase username: yourusername password: yourpassword driver-class-name: mybatis: mapper-locations: classpath:/mapper/*.xml type-aliases-package:
illustrate
- In YAML, indentation is used to represent hierarchical relationships. For example,
spring
andmybatis
It is a top-level configuration item.datasource
yesspring
subconfiguration items,url
、username
、password
anddriver-class-name
yesdatasource
subconfiguration items. - A space needs to be followed by a colon, and then the specific value is written.
Complete project example
The following is based on the aboveComplete project examples of configuration, including the sections mentioned earlier:
Project structure
src ├── main │ ├── java │ │ ├── com │ │ │ ├── example │ │ │ │ ├── demo │ │ │ │ │ ├── controller │ │ │ │ │ │ └── │ │ │ │ │ ├── entity │ │ │ │ │ │ └── │ │ │ │ │ ├── mapper │ │ │ │ │ │ ├── │ │ │ │ │ │ └── │ │ │ │ │ ├── service │ │ │ │ │ │ ├── │ │ │ │ │ │ └── impl │ │ │ │ │ │ └── │ │ │ │ │ └── │ └── resources │ ├── │ └── mapper │ └── └── test └── java └── com └── example └── demo └──
Dependency configuration()
<dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <dependency> <groupId></groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
Entity class ()
package ; public class User { private Long id; private String username; private String password; // Constructor public User() {} public User(String username, String password) { = username; = password; } // getters and setters public Long getId() { return id; } public void setId(Long id) { = id; } public String getUsername() { return username; } public void setUsername(String username) { = username; } public String getPassword() { return password; } public void setPassword(String password) { = password; } }
Mapper interface ()
package ; import ; import .*; import ; @Mapper public interface UserMapper { @Select("SELECT * FROM user") List<User> findAll(); @Select("SELECT * FROM user WHERE id = #{id}") User findById(Long id); @Insert("INSERT INTO user (username, password) VALUES (#{username}, #{password})") @Options(useGeneratedKeys = true, keyProperty = "id") void save(User user); @Update("UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}") void update(User user); @Delete("DELETE FROM user WHERE id = #{id}") void delete(Long id); }
Mapper map file()
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/"> <mapper namespace=""> <select resultType=""> SELECT * FROM user </select> <select resultType=""> SELECT * FROM user WHERE id = #{id} </select> <insert keyProperty="id" useGeneratedKeys="true"> INSERT INTO user (username, password) VALUES (#{username}, #{password}) </insert> <update > UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id} </update> <delete > DELETE FROM user WHERE id = #{id} </delete> </mapper>
Service layer
package ; import ; import ; public interface UserService { List<User> findAll(); User findById(Long id); void save(User user); void update(User user); void delete(Long id); }
package ; import ; import ; import ; import ; import ; import ; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return (); } @Override public User findById(Long id) { return (id); } @Override public void save(User user) { (user); } @Override public void update(User user) { (user); } @Override public void delete(Long id) { (id); } }
Controller layer ()
package ; import ; import ; import ; import ; import ; import .*; import ; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public ResponseEntity<List<User>> findAll() { List<User> users = (); return new ResponseEntity<>(users, ); } @GetMapping("/{id}") public ResponseEntity<User> findById(@PathVariable Long id) { User user = (id); if (user!= null) { return new ResponseEntity<>(user, ); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @PostMapping public ResponseEntity<Void> save(@RequestBody User user) { (user); return new ResponseEntity<>(); } @PutMapping public ResponseEntity<Void> update(@RequestBody User user) { (user); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @DeleteMapping("/{id}") public ResponseEntity<Void> delete(@PathVariable Long id) { (id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
test()
package ; import ; import ; import ; import ; import ; import static .*; @SpringBootTest public class DemoApplicationTests { @Autowired private UserService userService; @Test public void testFindAll() { assertEquals(0, ().size()); } @Test public void testSaveAndFindById() { User user = new User("testuser", "testpassword"); (user); assertNotNull((())); } @Test public void testUpdate() { User user = new User("testuser", "testpassword"); (user); ("newpassword"); (user); assertEquals("newpassword", (()).getPassword()); } @Test public void testDelete() { User user = new User("testuser", "testpassword"); (user); (()); assertNull((())); } }
Through the above configuration and code examples, you can use it in Spring Boot projectsConfiguration files to integrate MyBatis and implement complete user management functions.
The above is the detailed content of the detailed guide to using MyBatis in SpringBoot. For more information about using MyBatis in SpringBoot, please follow my other related articles!