阅读目录
一、什么是MyBatis
二、整合MyBatis
三、用注解方式使用 MyBatis
四、用配置方式使用 MyBatis
MyBatis 在Spring Boot应用非常广,非常强大的一个半自动的ORM框架。
代码下载:https://github.com/Jackson0714/study-spring-boot.git
05. 深入浅出 Spring Boot - 数据访问之JDBC(源码分析+代码下载)
06. 深入浅出 Spring Boot - 数据访问之Druid(附代码下载)
07. 深入浅出 Spring Boot - 数据访问之Mybatis(附代码下载)
回到顶部
一、什么是MyBatis
支持定制化SQL、存储过程以及高级映射的优秀的持久层框架
避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
可以对配置和原生Map使用简单的 XML 或注解
将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录
数据库、数据源、数据库连接池、JDBC、JDBC实现是什么关系?
JDBC:Java和关系型数据库的桥梁,是一个规范,不是实现。不同类型的数据库需要有自己的JDBC实现
数据源:包含数据库连接池,连接池管理。常见的有C3P0、HikariDataSoiurce、Druid等
连接池:预先创建一些数据库连接,放到连接池里面,用的时候从连接池里面取,用完后放回连接池
连接池管理:创建数据库连接,管理数据库连接
JDBC实现:MySQL JDBC实现、Oracle JDBC实现等其他实现
MyBatis对JDBC进行了封装
回到顶部
二、整合MyBatis
我们基于之前创建的项目spring-boot-06-data-druid 来创建spring-boot-07-data-mybatis项目
1)引入MyBatis依赖
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1
2)引入其他依赖
org.springframework.bootspring-boot-starter-webmysqlmysql-connector-javaruntimeio.springfoxspringfox-swagger22.9.2io.springfoxspringfox-swagger-ui2.9.2com.alibabadruid1.1.21
3)依赖图
回到顶部
三、用注解方式使用 MyBatis
1.准备创建department表的脚本
DROPTABLEIFEXISTS`department`;CREATETABLE`department`(`id`int(11)NOTNULLAUTO_INCREMENT,`department_name`varchar(255)DEFAULTNULL, PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=1DEFAULTCHARSET=utf8;
2.application.yml 自动执行脚本
initialization-mode:alwaysschema: - classpath:department.sql
执行一次后,注释 initialization-mode
# initialization-mode: always
3.创建department 实体类
packagecom.jackson0714.springboot.entity;publicclassDepartment{privateLong id;privateString departmentName;publicvoidsetId(Long id){this.id = id; }publicLonggetId(){returnid; }publicvoidsetDepartmentName(String departmentName){this.departmentName = departmentName; }publicStringgetDepartmentName(){returndepartmentName; }}
4.创建Mapper映射类,并将SQL注解到方法上
增删改查,你要的都在这里:
@MapperpublicinterfaceDepartmentMapper{@Select("select * from department") List> getAllDepartment();@Select("select * from department where id=#{id}")DepartmentgetDepartmentById(Long id);@Delete("delete from department where id=#{id}")intdeleteDepartment(Long id);@Insert("insert into department(department_name) values(#{departmentName})")intcreateDepartment(String departmentName);@Update("update department set department_name=#{departmentName} where id=#{id}")intupdateDepartmentById(Long id, String departmentName);}
5.创建MyBatis 配置类
增加自定义配置:如果表的字段名有下划线格式的,转为驼峰命名格式
@org.springframework.context.annotation.ConfigurationpublicclassMyBatisConfig{@BeanpublicConfigurationCustomizerconfigurationCustomizer(){returnnewConfigurationCustomizer() {@Overridepublicvoidcustomize(Configuration configuration){// 如果表的字段名有下划线格式的,转为驼峰命名格式configuration.setMapUnderscoreToCamelCase(true); } }; }}
6.创建DepartmentController
@Api(value ="DepartmentController", description ="部门controller")@RequestMapping("/v1/client")@RestControllerpublicclassDepartmentController{@AutowiredDepartmentMapper departmentMapper;@ApiOperation(value ="1.查询所有部门")@GetMapping("/dept/getAllDepartment")publicList> getAllDepartment() {returndepartmentMapper.getAllDepartment(); }@ApiOperation(value ="2.根据id查询某个部门")@ApiImplicitParams({@ApiImplicitParam(name ="id", value ="需要查询的部门id") })@GetMapping("/dept/{id}")publicDepartmentgetDepartmentById(@PathVariable Long id){returndepartmentMapper.getDepartmentById(id); }@ApiOperation(value ="3.新增部门")@ApiImplicitParams({@ApiImplicitParam(name ="name", value ="部门名称") })@PostMapping("/dept/create")publicintcreateDepartment(@RequestParam String name){returndepartmentMapper.createDepartment(name); }@ApiOperation(value ="4.根据id删除部门")@ApiImplicitParams({@ApiImplicitParam(name ="id", value ="需要删除的部门id") })@PostMapping("/dept/delete")publicintdeleteDepartment(@RequestParam Long id){returndepartmentMapper.deleteDepartment(id); }@ApiOperation(value ="5.根据id更新部门名称")@ApiImplicitParams({@ApiImplicitParam(name ="id", value ="需要更新的部门id"),@ApiImplicitParam(name ="name", value ="需要更新的部门名称") })@PostMapping("/dept/update")publicintupdateDepartmentById(@RequestParam Long id, @RequestParam String name){returndepartmentMapper.updateDepartmentById(id, name); }}
使用Swagger来测试
回到顶部
四、用配置方式使用 MyBatis
1. 文件结构
2. 创建user表的脚本
SETFOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for user-- ----------------------------DROPTABLEIFEXISTS`user`;CREATETABLE`user`(`user_id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'主键ID',`user_name`varchar(255)COLLATEutf8mb4_binNOTNULLCOMMENT'用户名',`password`varchar(255)COLLATEutf8mb4_binNOTNULL,`salt`varchar(255)COLLATEutf8mb4_binDEFAULTNULLCOMMENT'随机盐',`nickName`varchar(255)COLLATEutf8mb4_binNOTNULLCOMMENT'用户名',`phone`varchar(20)COLLATEutf8mb4_binDEFAULTNULLCOMMENT'手机号',`avatar`varchar(255)COLLATEutf8mb4_binDEFAULTNULLCOMMENT'头像',`mini_openId`varchar(32)COLLATEutf8mb4_binDEFAULTNULLCOMMENT'小程序OpenId',`lock_flag`char(1)COLLATEutf8mb4_binDEFAULT'0'COMMENT'0-正常,9-锁定',`del_flag`char(1)COLLATEutf8mb4_binDEFAULT'0'COMMENT'0-正常,1-删除',`create_time`timestampNOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间',`update_time`timestampNOTNULLDEFAULTCURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMPCOMMENT'更新时间', PRIMARYKEY(`user_id`),KEY`user_wx_openid`(`mini_openId`),KEY`user_idx1_username`(`user_name`))ENGINE=InnoDBAUTO_INCREMENT=4DEFAULTCHARSET=utf8mb4COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMICCOMMENT='用户表';
3. 插入一条User数据
INSERTINTOuser(user_name,password, nick_name, phone)values("jackson0714","123","悟空聊架构","123456")
4. 创建User实体类
packagecom.jackson0714.springboot.entity;importlombok.Data;importjava.sql.Timestamp;@DatapublicclassUser{privateLong userId;privateString userName;privateString password;privateString salt;privateString nickName;privateString phone;privateString avatar;privateString miniOpenId;privateString openId;privateBoolean lockFlag;privateBoolean delFlag;privateTimestamp createTime;privateTimestamp updateTime;}
需要安装Lombok插件
需要引入Lombok依赖
5. 创建调用User方法的 UserMapper 接口
// @Mapper 或MapperScan 将接口扫描装配到装配容器中publicinterfaceUserMapper{UsergetUserById(Long userId);}
6. 创建接口方法与SQL脚本的映射文件
SELECT * FROM user WHERE user_id=#{userId}
7. 创建UserController文件
@Api(value ="UserController", description ="用户controller")@RequestMapping("/v1/client")@RestControllerpublicclassUserController{@AutowiredUserMapper userMapper;@ApiOperation(value ="1.根据id查询某个用户")@ApiImplicitParams({@ApiImplicitParam(name ="需要查询的用户userId", value ="需要查询的用户userId") })@GetMapping("/emp/{userId}")publicUsergetUser(@PathVariable("userId")Long userId){returnuserMapper.getUserById(userId); }}
8. 添加MapperScan注解
@MapperScan(value ="com.jackson0714.springboot.mapper")@SpringBootApplicationpublicclassSpringboot07DataMybatisApplication{publicstaticvoidmain(String[] args){ SpringApplication.run(Springboot07DataMybatisApplication.class, args); }}
9.在Swagger上测试
10. 查看Druid监控
Spring Boot 整合MyBatis 讲完了,持续更新 《深入浅出 Spring Boot 系列》
代码下载:https://github.com/Jackson0714/study-spring-boot.git
05. 深入浅出 Spring Boot - 数据访问之JDBC(源码分析+代码下载)
06. 深入浅出 Spring Boot - 数据访问之Druid(附代码下载)
07. 深入浅出 Spring Boot - 数据访问之Mybatis(附代码下载)
关注公众号:悟空聊架构,
回复pmp,领取pmp资料!
回复悟空,领取架构师资料!
关注我,带你每天进步一点点!