1、导入依赖
-
- <dependency>
- <groupId>com.mysql</groupId>
- <artifactId>mysql-connector-j</artifactId>
- <version>8.1.0</version>
- </dependency>
-
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.1.4</version>
- </dependency>
-
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid-spring-boot-starter</artifactId>
- <version>1.2.16</version>
- </dependency>
复制代码 导入依赖的时候,需要根据自己所使用的Spring Boot和MySQL的版本而定。
2、创建数据库
我这里使用的是MySQL数据库。
首先创建一个mybatis_learn的数据库。然后创建一个student的表。- CREATE TABLE `student` (
- `id` int NOT NULL,
- `name` varchar(20) NOT NULL,
- `sex` tinyint NOT NULL COMMENT '0为女1为男'
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
复制代码 对应的,要实现一个Java的实体类,来对应数据库的表。- public class Student implements Serializable {
- private static final long serialVersionUID = -339516038496531943L;
- private String id;
- private String name;
- private String sex;
-
- // 省略了 get方法和set方法
- }
复制代码 3、配置文件
- # 数据源配置
- spring.datasource.druid.type=com.alibaba.druid.pool.DruidDataSource
- spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
- spring.datasource.druid.url=jdbc:mysql://localhost:3306/mybatis_learn?serverTimezone=UTC
- spring.datasource.druid.username=root
- spring.datasource.druid.password=123456
- # mybatis 配置
- # type aliases package是指定对应数据库实体类的包
- mybatis.type-aliases-package=com.example.spring_boot_mybatis.entity
- # 这里指定对应的xml文件
- mybatis.mapper-locations=classpath:mapper/*.xml
复制代码 4、编写各个文件

创建如图结构的各个包和文件。
(1)StudentMapper
这个接口是对应Mybatis的xml文件的接口,其中的方法对应每一种操作。- @Component
- @Mapper
- public interface StudentMapper {
- // 这里以查询为例子
- Student queryStudentById(Integer id);
- }
复制代码 (2)StudentService和StudentServiceImpl
- @Service("studentService")
- public class StudentServiceImpl implements StudentService {
- @Autowired
- private StudentMapper studentMapper;
- // 在这里调用了StudentMapper中的查询接口
- @Override
- public Student queryStudentById(Integer id) {
- return this.studentMapper.queryStudentById(id);
- }
- }
复制代码 (3)StudentMapper.xml
这个文件中就要写SQL的各种语句
其中开头的格式都是固定的。
namespace要对应写入上面mapper包中要实现的Mapper接口的类名。
在select语句中的id则要对应其中的方法名。- <?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.spring_boot_mybatis.mapper.StudentMapper">
- <select id="queryStudentById" resultType="student">
- select * from student where id = #{id}
- </select>
- </mapper>
复制代码 (4)编写Controller进行测试
- @RestController
- public class TestController {
- @Autowired
- private StudentService studentService;
- @RequestMapping(value = "/queryStudent", method = RequestMethod.GET)
- public Student queryStudentById(Integer id) {
- return this.studentService.queryStudentById(id);
- }
- }
复制代码 controller编写了一个查询接口,只要传入id就能返回数据库中的内容。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |