1. 导入依赖(一个是 MySQL的驱动,另外一个是MyBatis的框架)
<dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>2.3.1</version>
 </dependency>

<dependency>
       <groupId>com.mysql</groupId>
       <artifactId>mysql-connector-j</artifactId>
</dependency>

2.配置数据库连接信息(. yaml)中配置

spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
  1. 创建实体
public class Department {

    private Integer id;
    private String departmentName;
    
    // Setter and Getter
}
  1. 创建 Mapper

//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface DepartmentMapper {

    // 获取所有部门信息
    // @Select(" select * from department")
    List<Department> getDepartments();

    // 通过id获得部门
    // @Select("select * from department where id = #{id}")
    Department getDepartment(Integer id);
}
  1. 对应的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.mapper.DepartmentMapper">

    <select id="getDepartments" resultType="Department">
       select * from department;
    </select>

    <select id="getDepartment" resultType="Department" parameterType="int">
       select * from department where id = #{id};
    </select>

</mapper>
  1. mapper yaml的配置

    mybatis:
      mapper-locations: classpath:mybatis/mapper/*.xml
      type-aliases-package: com.example.demo_mybatis_test.pojo
    
7. Testing

@RestController
public class DepartmentController {


@Autowired
DepartmentMapper departmentMapper;

// 查询全部部门
@GetMapping("/getDepartments")
public List<Department> getDepartments(){
    return departmentMapper.getDepartments();
}

// 查询全部部门
@GetMapping("/getDepartment/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
    return departmentMapper.getDepartment(id);
}

}


phang
1 声望3 粉丝