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
目录
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监控
推荐阅读
-
SpringBoot无废话入门04:MyBatis整合
-
springboot+springmvc+mybatis项目整合
-
SpringBoot 整合jdbc和mybatis
-
SpringBoot整合mybatis访问时报错Invalid bound statement (not found)
-
Spring boot Mybatis整合构建Rest服务(超细版)
-
SpringBoot整合Mybatis,SpringMVC简单例子
-
【SpringBoot】廿六、SpringBoot中整合MyBatis-Plus
-
SpringBoot系列(五)Mybatis整合完整详细版
-
SpringBoot+Mybatis+Durid整合多数据源的三种方式,第一种
-
如何利用IDEA搭建SpringBoot项目整合mybatis实现简单的登录功能