1、导入 MyBatis 所需要的依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
2、配置数据库连接信息
spring.datasource.username=root
spring.datasource.password:
#?serverTimezone=UTC解决时区的报错
spring.datasource.url: jdbc:mysql://localhost:3306/student?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
3、测试数据库是否连接成功!
4、创建实体类
package com.luo.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
5、创建mapper目录以及对应的 Mapper 接口
//在Springboot05MybatisApplication()上@MapperScan("com.luo.mapper")扫描mapper
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository //dao层
public interface UserMapper {
List<User> getAll();
User queryById(int id);
}
6、对应的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.luo.mapper.UserMapper">
<select id="getAll" resultType="User">
select * from user;
</select>
<select id="queryById" resultType="User">
select * from user where id = #{id} ;
</select>
</mapper>
7、在配置文件中写入相应的配置
#整合mybatis
mybatis.type-aliases-package=com.luo.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
8、编写对应的Controller进行测试
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/all")
public List<User> alluser(){
return userMapper.getAll();
}
@GetMapping("/who/{id}")
public User queryById(@PathVariable("id") int id){
return userMapper.queryById(id);
}
}