使用 SpringBoot 和 MyBatis 框架从数据库读取数据

本文将介绍如何使用 SpringBoot 和 MyBatis 框架从 MySQL 数据库读取数据。

1. 添加依赖

在 pom.xml 文件中添加以下依赖:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- MyBatis Starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>
</dependencies>

2. 配置数据源

在 application.properties 文件中添加以下配置:

spring.datasource.url=jdbc:mysql://localhost:3306/database_name?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

其中,database_name 为你的数据库名,username 为你的数据库用户名,password 为你的数据库密码。

3. 创建 Entity 类

创建 Entity 类,该类对应数据库中的一张表:

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

4. 创建 Mapper 接口

创建 Mapper 接口,用于定义数据库操作的方法:

@Mapper
public interface UserMapper {
    @Select('SELECT * FROM user WHERE id = #{id}')
    User findById(Integer id);
}

5. 创建 Service 类

创建 Service 类,用于调用 Mapper 中的方法:

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User findById(Integer id) {
        return userMapper.findById(id);
    }
}

6. 创建 Controller 类

创建 Controller 类,用于处理 HTTP 请求:

@RestController
@RequestMapping('/user')
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping('/{id}')
    public User findById(@PathVariable Integer id) {
        return userService.findById(id);
    }
}

7. 启动应用程序

启动应用程序,访问 http://localhost:8080/user/1 即可获取 id 为 1 的用户信息。

示例

数据库表:

| id | name | email | |---|---|---| | 1 | John Doe | john.doe@example.com |

请求:

http://localhost:8080/user/1

响应:

{
  "id": 1,
  "name": "John Doe",
  "email": "john.doe@example.com"
}
SpringBoot & MyBatis: 从数据库读取数据