欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot整合Mybatis(配置文件版)

程序员文章站 2022-07-12 22:43:21
...

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

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

目录
SpringBoot整合Mybatis(配置文件版)

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;
    }

}

SpringBoot整合Mybatis(配置文件版)
SpringBoot整合Mybatis(配置文件版)
Druid的sql监控
SpringBoot整合Mybatis(配置文件版)