步骤 1: 创建新的 Spring Boot 项目
- 打开 IntelliJ IDEA。
- 选择 "File" > "New" > "Project..."。
- 在 "New Project" 对话框中,选择 "Spring Initializr"。
- 选择项目的基本配置,包括项目类型、语言、Spring Boot 版本等。
- 在 "Dependencies" 选项中,选择 "Spring Web" 和 "MyBatis Framework"。
- 点击 "Next" 按钮,指定项目的名称和位置。
- 点击 "Finish" 完成项目的创建。
步骤 2: 配置数据库连接
-
在
src/main/resources
目录下创建application.properties
文件。 -
在
application.properties
中配置数据库连接信息,例如:spring.datasource.url=jdbc:mysql://localhost:3306/your_database spring.datasource.username=your_username spring.datasource.password=your_password
步骤 3: 创建实体类
-
在
src/main/java/com/example/mybatis/model
目录下创建一个实体类(例如User.java
):package com.example.mybatis.model; public class User { // 类的定义,包括属性、构造方法等 }
步骤 4: 创建 Mapper 接口和 XML 文件
-
在
src/main/java/com/example/mybatis/mapper
目录下创建一个 MyBatis 的 Mapper 接口(例如UserMapper.java
):package com.example.mybatis.mapper; import com.example.mybatis.model.User; import java.util.List; public interface UserMapper { List<User> getAllUsers(); // 其他方法定义 }
在
src/main/resources/mybatis/mapper
目录下创建与上述 Mapper 接口对应的 XML 文件(例如UserMapper.xml
):<!-- mybatis/mapper/UserMapper.xml --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mybatis.mapper.UserMapper"> <!-- SQL语句等配置 --> </mapper>
步骤 5: 创建 Service 类
-
在
src/main/java/com/example/mybatis/service
目录下创建 Service 类(例如UserService.java
):package com.example.mybatis.service; import com.example.mybatis.model.User; import java.util.List; public interface UserService { List<User> getAllUsers(); // 其他方法定义 }
步骤 6: 创建 Controller 类
-
在
src/main/java/com/example/mybatis/controller
目录下创建一个控制器类(例如SampleController.java
):package com.example.mybatis.controller; import com.example.mybatis.service.UserService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/api/users") public class SampleController { private final UserService userService; public SampleController(UserService userService) { this.userService = userService; } @GetMapping public List<User> getAllUsers() { return userService.getAllUsers(); } }
步骤 7: 运行项目
- 在 IntelliJ IDEA 中,找到并运行
MyBatisSpringBootApplication.java
中的main
方法。 - 应用程序将启动,你可以通过浏览器或工具(例如 Postman)访问
http://localhost:8080/api/users
来测试接口。