本篇是SpringBoot项目实战(4):集成Mybatis和SpringBoot项目实战(5):集成分页插件这两篇的修订版。
本文知识点:
- springboot如何集成mybatis
- springboot如何集成通用mapper
- springboot如何集成pagehelper分页插件
- 如何通过xml、通用mapper和注解这三种方式查询数据库
注[1]:本文(本系列)所有涉及到数据库的内容,默认使用MySQL5.6,高于或低于这个版本时可能会存在兼容问题,具体问题,请自行查阅相关资料。
注[2]:本文例子中涉及到Freemarker相关内容,请参考springboot整合Freemark模板(修订-详尽版)
准备工作
目录结构
└─me
└─zhyd
└─springboot
└─mybatis
├─config
├─controller
├─entity
├─mapper
├─service
│ └─impl
└─util
准备数据库
DROP TABLE IF EXISTS `message`;
CREATE TABLE `message` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`nick_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称',
`ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'IP',
`insert_time` datetime(0) NULL DEFAULT NULL COMMENT '提交时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
└─me
└─zhyd
└─springboot
└─mybatis
├─config
├─controller
├─entity
├─mapper
├─service
│ └─impl
└─util
准备数据库
DROP TABLE IF EXISTS `message`;
CREATE TABLE `message` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`nick_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称',
`ip` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'IP',
`insert_time` datetime(0) NULL DEFAULT NULL COMMENT '提交时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
注:为方便测试,此处可以使用存储过程批量插入一些测试例子
DROP PROCEDURE IF EXISTS `autoInsert`; delimiter ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `autoInsert`() BEGIN DECLARE i INT DEFAULT 0 ; -- 开始 SET autocommit = 0 ; -- 结束 WHILE (i <= 100) DO REPLACE INTO message ( `id`, `nick_name`, `ip`, `insert_time` ) VALUE ( i, '码一码', '127.0.0.1', NOW() ) ; SET i = i + 1 ; END WHILE ; SET autocommit = 1 ; COMMIT ; END ;; delimiter ;
使用call autoInsert();调用存储过程即可。本例使用100条数据作为测试
添加依赖
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
tk.mybatis
mapper-spring-boot-starter
1.1.4
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.9
mysql
mysql-connector-java
runtime
配置属性文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_learning?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
# MyBatis
mybatis:
type-aliases-package: com.zyd.mybatis.com.rest.entity
mapper-locations: classpath:/mybatis
@RequestMapping("/listByMapperXml/{currentPage}/{pageSize}")
public String listByMapperXml(Model model, @PathVariable("currentPage") int currentPage,
@PathVariable("pageSize") int pageSize) {
PageHelper.startPage(currentPage, pageSize);
model.addAttribute("selectTypeMsg", "通过自定义的mapper xml查询");
model.addAttribute("selectType", "listByMapperXml");
model.addAttribute("page", new PageInfo<>(messageService.listByMapperXml()));
return "index";
}
@RequestMapping("/listByMapper/{currentPage}/{pageSize}")
public String listByMapper(Model model, @PathVariable("currentPage") int currentPage,
@PathVariable("pageSize") int pageSize) {
PageHelper.startPage(currentPage, pageSize);
model.addAttribute("selectTypeMsg", "通过通用mapper查询");
model.addAttribute("selectType", "listByMapper");
model.addAttribute("page", new PageInfo<>(messageService.listByMapper()));
return "index";
}
@RequestMapping("/listByAnnotation/{currentPage}/{pageSize}")
public String listByAnnotation(Model model, @PathVariable("currentPage") int currentPage,
@PathVariable("pageSize") int pageSize) {
PageHelper.startPage(currentPage, pageSize);
model.addAttribute("selectTypeMsg", "通过注解查询");
model.addAttribute("selectType", "listByAnnotation");
model.addAttribute("page", new PageInfo<>(messageService.listByAnnotation()));
return "index";
}
}
编写页面
Spring Boot 集成Mybatis + Mapper + Pagehelper 测试例子
Spring Boot 集成Mybatis + Mapper + Pagehelper 测试例子
${.now?string("yyyy-MM-dd HH:mm:ss.sss")}
${selectTypeMsg}
<#if page.list?exists>
当前页共 ${page.list?size }条记录,总共${page.total!(0)}条记录
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_learning?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
# MyBatis
mybatis:
type-aliases-package: com.zyd.mybatis.com.rest.entity
mapper-locations: classpath:/mybatis
@RequestMapping("/listByMapperXml/{currentPage}/{pageSize}")
public String listByMapperXml(Model model, @PathVariable("currentPage") int currentPage,
@PathVariable("pageSize") int pageSize) {
PageHelper.startPage(currentPage, pageSize);
model.addAttribute("selectTypeMsg", "通过自定义的mapper xml查询");
model.addAttribute("selectType", "listByMapperXml");
model.addAttribute("page", new PageInfo<>(messageService.listByMapperXml()));
return "index";
}
@RequestMapping("/listByMapper/{currentPage}/{pageSize}")
public String listByMapper(Model model, @PathVariable("currentPage") int currentPage,
@PathVariable("pageSize") int pageSize) {
PageHelper.startPage(currentPage, pageSize);
model.addAttribute("selectTypeMsg", "通过通用mapper查询");
model.addAttribute("selectType", "listByMapper");
model.addAttribute("page", new PageInfo<>(messageService.listByMapper()));
return "index";
}
@RequestMapping("/listByAnnotation/{currentPage}/{pageSize}")
public String listByAnnotation(Model model, @PathVariable("currentPage") int currentPage,
@PathVariable("pageSize") int pageSize) {
PageHelper.startPage(currentPage, pageSize);
model.addAttribute("selectTypeMsg", "通过注解查询");
model.addAttribute("selectType", "listByAnnotation");
model.addAttribute("page", new PageInfo<>(messageService.listByAnnotation()));
return "index";
}
}
编写页面
Spring Boot 集成Mybatis + Mapper + Pagehelper 测试例子
Spring Boot 集成Mybatis + Mapper + Pagehelper 测试例子
${.now?string("yyyy-MM-dd HH:mm:ss.sss")}
${selectTypeMsg}
<#if page.list?exists>
当前页共 ${page.list?size }条记录,总共${page.total!(0)}条记录
${selectTypeMsg} <#if page.list?exists>
当前页共 ${page.list?size }条记录,总共${page.total!(0)}条记录
| ${message.id} | ${message.ip} | ${message.nickName} | ${message.insertTime?string('yyyy-MM-dd HH:mm:ss.SSS')} |
|
|||
Author: https://www.zhyd.me @码一码
运行测试
listByMapperXml
listByMapper
listByAnnotation
到此为止,本篇已详细介绍了在springboot中如何整合Mybatis + Mapper,以及使用Pagehelper实现分页的使用方法。
还是那句话
我可以对一个人无限的好,前提是值得。 ——慕冬雪



