SpringBoot整合Mybatis(配置文件版)

1.指定全局配置文件和Mapper映射文件的位置

mybatis:
	#Mybatis全局配置文件的位置
  config-location: classpath:mybatis/mybatis-config.xml
  	#Mapper 指定sql映射文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml

目录
在这里插入图片描述

2.编写接口

import cn.yf.springboot_mybatis.bean.Employee;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);

    public void insertEmployee(Employee employee);

}

写法和SSM一样,只不过要加上@Mapper,也可以在SpringBootApplication上添加@MapperScan(value = “cn.yf.springboot_mybatis.mapper”),这样mapper包下就不用添加@Mapper

3.配置文件的编写

mybatis-config.xml(可以从mybatis官方文档获得模板)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

关于mybatis的配置写在configuration标签中
Mapper.xml(可以从mybatis官方文档获得模板)

<?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="cn.yf.springboot_mybatis.mapper.EmployeeMapper">
<!--   public Employee getEmployeeById(Integer id);

    public void insertEmployee(Employee employee); -->
    <select id="getEmployeeById" parameterType="Integer" resultType="cn.yf.springboot_mybatis.bean.Employee">
        select * from employee where id = #{id}
    </select>
<!--    this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.d_id = d_id;-->
    <insert id="insertEmployee" parameterType="cn.yf.springboot_mybatis.bean.Employee" useGeneratedKeys="true" keyProperty="id">
        insert into employee (lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{d_id})
    </insert>
</mapper>

编写方法就和SSM一样的

4.测试

@RestController
public class EmployeeController {

    @Resource
    EmployeeMapper employeeMapper;

    @GetMapping("emp/{id}")
    public Employee getEmployeeById(@PathVariable("id") Integer id){
        return employeeMapper.getEmployeeById(id);
    }

    @GetMapping("emp")
    public Employee insertEmployee(Employee employee){
        employeeMapper.insertEmployee(employee);
        return employee;
    }

}

在这里插入图片描述
在这里插入图片描述
Druid的sql监控
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值