SpringBoot整合Mybatis
程序员文章站
2022-06-05 16:06:27
...
我们引入上一章节的Druid配置文件,并且建立两张表,如下所示:
当然,我们也可以写一个sql文件,再用深入理解springboot(5)的方法,也能得到同样的结果。
我们建立两个bean——>Department and Employee:
public class Department {
private Integer d_id;
private String d_name;
....省去get/set
}
public class Employee {
private Integer id;
private String lastname;
private String email;
private Integer gender;
private Integer d_id;
....省去get/set
}
然后建立一个mapper.DepartmentMapper
@Mapper
public interface DepartmentMapper {
@Select("select * from department where d_id=#{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where d_id=#{id}")
public int deleteDeptById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "d_id")//告诉注解版的mybatis【department】对象中的id为自增主键
@Insert("insert into department(d_id, d_name) values(#{d_id},#{d_name})")
public int insertDept(Department department);
@Update("update department set d_name=#{d_name} where d_id=#{d_id}")
public int updateDept(Department department);
}
最后,再安排一个Controller.DeptController:
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
}
当然,为了方便起见(其实也没方便什么!!),我们可以去掉@Mapper
,用一个@MapperScan
加到启动类上面,相当于指定给 mapper包下面的所有的类都加上@Mapper
一样,批量扫描所有的接口:
@MapperScan(value = "com.king.mybatis.mapper")
@SpringBootApplication
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
还有XML配置的方法,这个之前学过,就不再赘述。
上一篇: 贪食蛇
推荐阅读
-
Apache shiro的简单介绍与使用教程(与spring整合使用)
-
SpringBoot起飞系列-拦截器和统一错误处理(七)
-
SpringBoot2.x升级踩坑--新增Configuration property name限制
-
springboot切面添加日志功能实例详解
-
Java 排序算法整合(冒泡,快速,希尔,拓扑,归并)
-
Spring Boot 2.X整合Spring-cache(让你的网站速度飞起来)
-
微信小程序整合使用富文本编辑器的方法详解
-
一起学MyBatis之入门篇(2)
-
MyBatis的使用
-
SpringBoot 源码解析 (七)----- Spring Boot的核心能力 - SpringBoot如何实现SpringMvc的?