学习视频链接,以示尊重:https://www.bilibili.com/video/BV1PE411i7CV?p=51
一、SpringBoot整合MyBatis
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.1.3</version>
</dependency>
2、配置数据库连接信息(和上一节所学SpringBoot继承Druid所配置信息相同)
3、创建实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
4、创建mapper目录以及对应的 Mapper 接口:
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface DepartmentMapper {
// 获取所有部门信息
List<Department> getDepartments();
// 通过id获得部门
Department getDepartment(Integer id);
}
5、对应地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..xingyu.springbootlearn.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>
或者直接使用注解:
@Mapper
@Repository
public interface DepartmentMapper {
// 获取所有部门信息
@Select("select * from department")
List<Department> getDepartments();
// 通过id获得部门
@Select("select * from department where id = #{id}")
Department getDepartment(@Param