MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
# 配置mybatis实体和xml映射
mybatis:
# 这里的classpath对应的就是resources目录
mapper-locations: classpath:mapper/*.xml
configuration:
# 配置日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true举例:
驼峰:departmentId
下划线:department_id
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="">
</mapper>namespace对应的就mapper的接口的全限定类名,方法名对应<select>或<update>的id
xml和接口是一一对应的
需要告诉springboot如何扫描mapper包,把他注册为Spring中的bean,这样就可以在Serivice中自动注入

并且创建Service并且标注为spring中的bean





可以看到路径上用的是? &拼接参数

传递多个参数


对象参数

<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
<exclusions>
<exclusion>
<artifactId>mybatis</artifactId>
<groupId>mybatis</groupId>
</exclusion>
</exclusions>
</dependency>public PageInfo<Employee> selectPage(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Employee> list = employeeMapper.selectAll();
return PageInfo.of(list);
}@GetMapping("/selectPage")
public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize) {
PageInfo<Employee> pageInfo = employeeService.selectPage(pageNum, pageSize);
return Result.success(pageInfo);
}
get查询操作
post新增操作
@RequestBody可以把前端传来的json字符串映射成java的对象或者数组
mybatis里面写sql使用下划线,涉及到绑定java对象值,就写驼峰
<insert id="add" parameterType="org.example.entity.Employee">
insert into employee(name,no,description,sex,department_id) values(#{name},#{no},#{description},#{sex},#{departmentId})
</insert>/**
* 添加数据
*/
@PostMapping("/add")
public Result add(@RequestBody Employee employee) {
employeeService.add(employee);
return Result.success();
}@RequestBody表示接收的是一个json对象,否则会抛出异常
put修改操作
<update id="updateById" parameterType="org.example.entity.Employee">
update employee set name = #{name},no = #{no},description = #{description},sex = #{sex},department_id = #{departmentId} where id = #{id}
</update>/**
* 更新数据
*/
@PutMapping("/update")
public Result update(@RequestBody Employee employee) {
employeeService.update(employee);
return Result.success();
}
一定要有id,否则更新的是空数据
delete删除操作
/**
* 删除数据
*/
@DeleteMapping("/delete/{id}")
public Result delete(@PathVariable Integer id) {
employeeService.delete(id);
return Result.success();
}<delete id="deleteById">
delete from employee where id = #{id}
</delete>