使用Spring Boot和MyBatis连接MySQL数据库

在开发Java应用程序时,连接数据库是一个常见的需求。Spring Boot和MyBatis是两个流行的框架,可以帮助我们更轻松地实现与数据库的交互。在本文中,我们将介绍如何使用Spring Boot和MyBatis连接MySQL数据库,并提供代码示例帮助您快速上手。

准备工作

在开始之前,确保您已经安装了MySQL数据库,并创建了一个数据库以供我们之后的操作。同时,我们还需要准备一个Spring Boot项目,可以通过Spring Initializr来快速搭建一个基本的Spring Boot项目。

引入依赖

首先,我们需要在pom.xml文件中引入MyBatisMySQL的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

配置数据库连接

application.properties文件中配置数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/my_database
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

创建实体类和Mapper

接下来,我们需要创建一个实体类和对应的Mapper接口:

public class User {
    private Long id;
    private String name;
    private Integer age;
    
    // 省略getter和setter方法
}

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User getUserById(Long id);
    
    @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
    void insertUser(User user);
}

编写Service

接着,我们创建一个Service类,用于调用Mapper中的方法:

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }
    
    public void insertUser(User user) {
        userMapper.insertUser(user);
    }
}

编写Controller

最后,我们创建一个Controller类,用于处理前端请求:

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    
    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    
    @PostMapping("/user")
    public void insertUser(@RequestBody User user) {
        userService.insertUser(user);
    }
}

类图

classDiagram
    User <|-- UserMapper
    UserMapper ..> User : 使用
    
    class User {
      Long id
      String name
      Integer age
    }
    class UserMapper {
      +getUserById(Long id) : User
      +insertUser(User user) : void
    }

状态图

stateDiagram
    [*] --> Created
    Created --> Active : call getUserById
    Active -->[*] : call insertUser

总结

通过本文的介绍,您已经学会了如何使用Spring Boot和MyBatis连接MySQL数据库,并实现了基本的增删改查操作。希望这对您有所帮助,祝您编程愉快!