- 在创建SpringBoot时要选择添加MyBatis依赖和MySQL驱动,
创建好后会在pom.xml
文件中加入
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 创建要操作表对应的实体类,如我有一张student表,该表有三个主键,分别是id、name、age。
创建如下实体类:
public class Student {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 创建 Dao 接口
@Mapper
public interface StudentDao {
Student selectById(@Param("stuId") Integer id);
}
在 Dao 接口的同一目录中创建 mapper 文件
<?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.gushi.springboot.dao.StudentDao">
<select id="selectById" resultType="com.gushi.springboot.model.Student">
select id,name,age from student where id=#{stuId}
</select>
</mapper>
- 在
pom.xml
中加入 resource 插件,指定把src/main/java目录中的xml
文件包含到classpath中
<resources>
<resource>
<directory>src\main\java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
- 创建 service 接口
public interface StudentService {
Student queryStudent(Integer id);
}
- 创建 service 接口实现类
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDao studentDao;
@Override
public Student queryStudent(Integer id) {
Student student = studentDao.selectById(id);
return student;
}
}
- 创建 controller 类
@Controller
public class StudentController {
@Resource
private StudentService studentService;
@RequestMapping("/query")
@ResponseBody
public String queryStudent(Integer id){
Student student = studentService.queryStudent(id);
return student.toString();
}
}
- 在
application.properties
文件中配置数据库的连接信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
https://www.bilibili.com/video/BV1XQ4y1m7ex?p=41