前言
繼續(xù)Springboot5 開發(fā)常用技術(shù)整合--筆記
https://yunpan.#/surl_yLKZ52FG45K (提取碼:1a6e)
涉及到的知識點
- 用navicat創(chuàng)建mysq數(shù)據(jù)庫及表結(jié)構(gòu)
- Spring-Boot整合--MyBatis
- Spring-Boot整合--阿里druid數(shù)據(jù)庫連接池
- Spring-Boot整合--mysql-connector
- 在idea開發(fā)環(huán)境中利用MyBatis Generator 插件,用于數(shù)據(jù)庫逆向生成Dao哆窿、Model链烈、Mapping相關(guān)文件
- tk.mybatis.mapper 第三方通用mapper https://github.com/abel533/MyBatis-Spring-Boot
- 推特的id生成器idworker
- pageHelper插件
- 自定義mapper
- mybatis ---事務(wù)處理
- IntelliJ IDEA 連接數(shù)據(jù)庫 詳細(xì)過程
- Spring Boot中使用MyBatis注解配置詳解-今日頭條
8 Springboot整合MyBatis
用Navicat創(chuàng)建mysql數(shù)據(jù)庫 leecx
并執(zhí)行sql腳本leecx.sql,執(zhí)行后的
leecx.sql腳本
/*
Navicat MySQL Data Transfer
Source Server : .
Source Server Version : 50505
Source Host : localhost:3306
Source Database : leecx
Target Server Type : MYSQL
Target Server Version : 50505
File Encoding : 65001
Date: 2018-03-29 16:29:17
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for data_dict
-- ----------------------------
DROP TABLE IF EXISTS `data_dict`;
CREATE TABLE `data_dict` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type_name` varchar(64) NOT NULL COMMENT '數(shù)據(jù)字典類型名稱',
`type_code` varchar(64) DEFAULT NULL COMMENT '數(shù)據(jù)字典類型代碼',
`ddkey` varchar(6) NOT NULL COMMENT '數(shù)據(jù)鍵',
`ddvalue` varchar(12) NOT NULL COMMENT '數(shù)據(jù)值',
`is_show` int(1) NOT NULL COMMENT '是否顯示冷守,1:顯示胶滋;2:不顯示',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COMMENT='數(shù)據(jù)字典表';
-- ----------------------------
-- Records of data_dict
-- ----------------------------
INSERT INTO `data_dict` VALUES ('1', '性別', 'sex', '0', '女', '1');
INSERT INTO `data_dict` VALUES ('2', '性別', 'sex', '1', '男', '1');
INSERT INTO `data_dict` VALUES ('3', '性別', 'sex', '2', '保密', '1');
INSERT INTO `data_dict` VALUES ('4', '汽車類型', 'carType', '2', '公交車', '1');
INSERT INTO `data_dict` VALUES ('5', '汽車類型', 'carType', '1', '轎車', '1');
INSERT INTO `data_dict` VALUES ('6', '職業(yè)', 'job', '1', 'Java開發(fā)', '1');
INSERT INTO `data_dict` VALUES ('7', '職業(yè)', 'job', '2', '前端開發(fā)', '1');
INSERT INTO `data_dict` VALUES ('8', '職業(yè)', 'job', '3', '大數(shù)據(jù)開發(fā)', '1');
INSERT INTO `data_dict` VALUES ('9', '職業(yè)', 'job', '4', 'ios開發(fā)', '1');
INSERT INTO `data_dict` VALUES ('10', '職業(yè)', 'job', '5', 'Android開發(fā)', '1');
INSERT INTO `data_dict` VALUES ('11', '職業(yè)', 'job', '6', 'Linux系統(tǒng)工程師', '1');
INSERT INTO `data_dict` VALUES ('12', '職業(yè)', 'job', '7', 'PHP開發(fā)', '1');
INSERT INTO `data_dict` VALUES ('13', '職業(yè)', 'job', '8', '.net開發(fā)', '1');
INSERT INTO `data_dict` VALUES ('14', '職業(yè)', 'job', '9', 'C/C++', '1');
INSERT INTO `data_dict` VALUES ('15', '職業(yè)', 'job', '10', '學(xué)生', '0');
INSERT INTO `data_dict` VALUES ('16', '職業(yè)', 'job', '11', '其它', '1');
INSERT INTO `data_dict` VALUES ('17', '職業(yè)', 'job', '12', '全棧牛逼架構(gòu)師', '1');
INSERT INTO `data_dict` VALUES ('18', '汽車類型', 'carType', '3', '海陸兩用', '1');
-- ----------------------------
-- Table structure for demo_item
-- ----------------------------
DROP TABLE IF EXISTS `demo_item`;
CREATE TABLE `demo_item` (
`id` varchar(20) NOT NULL,
`name` varchar(255) NOT NULL,
`amount` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of demo_item
-- ----------------------------
INSERT INTO `demo_item` VALUES ('170909FRA2NB7TR4', '紅翼 red wing', '215000');
INSERT INTO `demo_item` VALUES ('170909FRB9DPXY5P', '紅翼 9111', '210000');
INSERT INTO `demo_item` VALUES ('170909FRCAT15XGC', '紅翼 875', '215000');
INSERT INTO `demo_item` VALUES ('170909FRF2P18ARP', 'cat', '185000');
INSERT INTO `demo_item` VALUES ('170909FRG6R75PZC', 'dog', '195000');
INSERT INTO `demo_item` VALUES ('170909FRHBS3K680', '馬丁靴', '150000');
INSERT INTO `demo_item` VALUES ('170909FRPWA5HCPH', '天木蘭 經(jīng)典 船鞋', '65000');
INSERT INTO `demo_item` VALUES ('170909FRS6SBHH00', '天木蘭 踢不爛', '65000');
INSERT INTO `demo_item` VALUES ('170909FRX22HKCDP', '其樂 袋鼠靴', '70000');
-- ----------------------------
-- Table structure for sys_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`name` varchar(128) NOT NULL COMMENT '資源名稱',
`type` int(2) NOT NULL COMMENT '資源類型:\r\n0:頂級根權(quán)限\r\n1:菜單,間接代表就是 isParent=true\r\n2:普通鏈接(按鈕孔轴,link等)',
`url` varchar(128) DEFAULT NULL COMMENT '訪問url地址',
`percode` varchar(128) DEFAULT NULL COMMENT '權(quán)限代碼字符串',
`parentid` int(11) DEFAULT NULL COMMENT '父結(jié)點id\r\n為0代表根節(jié)點',
`parentids` varchar(128) DEFAULT NULL COMMENT '父結(jié)點id列表串',
`sort` int(3) DEFAULT NULL COMMENT '排序號',
`available` int(1) NOT NULL COMMENT '是否可用,1:可用麸澜,0不可用',
`description` varchar(128) DEFAULT NULL COMMENT '當(dāng)前資源描述',
`create_time` datetime NOT NULL,
`update_time` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `percode` (`percode`)
) ENGINE=InnoDB AUTO_INCREMENT=258 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of sys_permission
-- ----------------------------
INSERT INTO `sys_permission` VALUES ('237', '個人會員', '1', '/appuser/mng', 'appuser:mng', '216', null, null, '1', '會員管理 - 個人會員 菜單按鈕', '2016-10-24 14:28:31', '2016-10-24 14:28:31');
INSERT INTO `sys_permission` VALUES ('238', '查看', '2', '/appuser/getPersonal', 'appuser:getPersonal', '237', null, null, '1', '會員管理 - 個人會員 下屬按鈕', '2016-10-24 14:36:42', '2016-10-24 14:36:55');
INSERT INTO `sys_permission` VALUES ('239', '審核', '2', '/appuser/toCheck', 'appuser:toCheck', '237', null, null, '1', '會員管理 - 個人會員 下屬按鈕', '2016-10-24 14:37:37', '2016-10-24 14:37:45');
INSERT INTO `sys_permission` VALUES ('240', '提交審核', '2', '/appuser/check', 'appuser:check', '237', null, null, '1', '會員管理 - 個人會員 菜單按鈕', '2016-10-24 14:39:10', '2016-10-24 14:39:10');
INSERT INTO `sys_permission` VALUES ('241', '企業(yè)會員', '1', '/company/mng', 'company:mng', '216', null, null, '1', '會員管理 - 企業(yè)會員', '2016-10-24 14:41:52', '2016-10-24 14:42:11');
INSERT INTO `sys_permission` VALUES ('242', '查看', '2', '/company/getCompany', 'company:getCompany', '241', null, null, '1', '會員管理 - 企業(yè)會員 下查看資源', '2016-10-24 14:43:38', '2016-10-24 14:43:43');
INSERT INTO `sys_permission` VALUES ('243', '審核', '2', '/company/toCheck', 'company:toCheck', '241', null, null, '1', '會員管理 - 企業(yè)會員', '2016-10-24 14:44:23', '2016-10-24 14:44:23');
INSERT INTO `sys_permission` VALUES ('244', '提交審核', '2', '/company/check', 'company:check', '241', null, null, '1', '會員管理 - 企業(yè)會員', '2016-10-24 14:44:52', '2016-10-24 14:44:59');
INSERT INTO `sys_permission` VALUES ('245', '車輛管理', '1', '/cars/toCarsList', 'cars:toCarsList', '216', null, null, '1', '車輛管理菜單', '2016-10-26 13:51:20', '2016-10-26 13:51:20');
INSERT INTO `sys_permission` VALUES ('246', '查看', '2', '/cars/queryCars', 'cars:queryCars', '245', null, null, '1', '車輛管理菜單 - 查看按鈕', '2016-10-26 13:52:34', '2016-10-26 13:52:42');
INSERT INTO `sys_permission` VALUES ('247', '審核', '2', '/cars/toCarsCheck', 'cars:toCarsCheck', '245', null, null, '1', '車輛管理菜單 - 審核按鈕', '2016-10-26 13:53:19', '2016-10-26 13:53:19');
INSERT INTO `sys_permission` VALUES ('248', '提交審核', '2', '/cars/carsCheck', 'cars:carsCheck', '245', null, null, '1', '車輛管理菜單 - 提交審核', '2016-10-26 13:54:08', '2016-10-26 13:54:08');
INSERT INTO `sys_permission` VALUES ('249', '車源管理', '1', '/carsource/mng', 'carsource:mng', '216', null, null, '1', '貨源/車源管理 - 車源管理', '2016-10-26 13:55:28', '2016-10-26 13:55:28');
INSERT INTO `sys_permission` VALUES ('250', '貨源管理', '1', '/cargosource/mng', 'cargosource:mng', '216', null, null, '1', '車源/貨源管理菜單 - 貨源管理', '2016-10-26 13:56:52', '2016-10-26 13:56:52');
INSERT INTO `sys_permission` VALUES ('252', '搜索車源', '2', '/carsource/getAll', 'carsource:getAll', '249', null, null, '1', '貨源/車源管理 - 車源管理 - 搜索', '2016-10-26 13:59:19', '2016-10-26 13:59:19');
INSERT INTO `sys_permission` VALUES ('254', '新增車源', '2', '/carsource/add', 'carsource:add', '249', null, null, '1', '貨源/車源管理 - 車源管理 - 新增車源', '2016-10-26 14:03:36', '2016-10-26 14:03:36');
INSERT INTO `sys_permission` VALUES ('255', '車源詳情', '2', '/carsource/detail', 'carsource:detail', '249', null, null, '1', '貨源/車源管理 - 車源管理 - 車源詳情', '2016-10-26 14:04:03', '2016-10-26 14:04:03');
INSERT INTO `sys_permission` VALUES ('256', '刪除車源', '2', '/carsource/del', 'carsource:del', '249', null, null, '1', '貨源/車源管理 - 車源管理 - 刪除車源', '2016-10-26 14:05:26', '2016-10-26 14:05:35');
INSERT INTO `sys_permission` VALUES ('257', '保存新增的車源', '2', '/carsource/save', 'carsource:save', '249', null, null, '1', '貨源/車源管理 - 車源管理 - 保存新增的車源', '2016-10-26 14:06:52', '2016-10-26 14:06:58');
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`available` int(1) DEFAULT NULL COMMENT '是否可用,1:可用奸晴,0不可用',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('1', '超級管理員', '1');
INSERT INTO `sys_role` VALUES ('2', '總經(jīng)理', '1');
INSERT INTO `sys_role` VALUES ('3', '客服', '1');
INSERT INTO `sys_role` VALUES ('4', '銷售/市場專員', '1');
INSERT INTO `sys_role` VALUES ('5', '產(chǎn)品團(tuán)隊', '1');
INSERT INTO `sys_role` VALUES ('6', '技術(shù)團(tuán)隊', '1');
-- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`sys_role_id` int(20) NOT NULL COMMENT '角色id',
`sys_permission_id` int(20) NOT NULL COMMENT '權(quán)限id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of sys_role_permission
-- ----------------------------
INSERT INTO `sys_role_permission` VALUES ('1', '1', '237');
INSERT INTO `sys_role_permission` VALUES ('2', '1', '238');
INSERT INTO `sys_role_permission` VALUES ('3', '1', '239');
INSERT INTO `sys_role_permission` VALUES ('4', '1', '240');
INSERT INTO `sys_role_permission` VALUES ('5', '1', '241');
INSERT INTO `sys_role_permission` VALUES ('6', '6', '250');
INSERT INTO `sys_role_permission` VALUES ('7', '6', '251');
INSERT INTO `sys_role_permission` VALUES ('8', '6', '252');
INSERT INTO `sys_role_permission` VALUES ('9', '6', '253');
INSERT INTO `sys_role_permission` VALUES ('10', '6', '254');
INSERT INTO `sys_role_permission` VALUES ('11', '6', '255');
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` varchar(20) NOT NULL,
`username` varchar(60) NOT NULL COMMENT '用戶名拇厢,登錄名',
`password` varchar(64) NOT NULL COMMENT '密碼',
`nickname` varchar(60) NOT NULL COMMENT '昵稱',
`age` int(3) DEFAULT NULL COMMENT '年齡',
`sex` int(1) DEFAULT NULL COMMENT '性別\r\n0:女\r\n1:男\(zhòng)r\n2:保密 ',
`job` int(10) DEFAULT NULL COMMENT '職業(yè)類型:\r\n1:Java開發(fā)\r\n2:前端開發(fā)\r\n3:大數(shù)據(jù)開發(fā)\r\n4:ios開發(fā)\r\n5:Android開發(fā)\r\n6:Linux系統(tǒng)工程師\r\n7:PHP開發(fā)\r\n8:.net開發(fā)\r\n9:C/C++\r\n10:學(xué)生\r\n11:其它',
`face_image` varchar(255) DEFAULT NULL COMMENT '頭像地址',
`province` varchar(12) DEFAULT NULL COMMENT '省',
`city` varchar(12) DEFAULT NULL COMMENT '市',
`district` varchar(12) DEFAULT NULL COMMENT '區(qū)',
`address` varchar(128) DEFAULT NULL COMMENT '詳細(xì)地址',
`auth_salt` varchar(16) DEFAULT NULL COMMENT '用于權(quán)限的“鹽”',
`last_login_ip` varchar(20) DEFAULT NULL COMMENT '最后一次登錄IP',
`last_login_time` datetime DEFAULT NULL COMMENT '最后一次登錄時間',
`is_delete` int(1) NOT NULL,
`regist_time` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系統(tǒng)后臺用戶';
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1001', 'test', '72e1242b855fb038212135e0ad348842', 'lee123', null, null, null, null, null, null, null, null, 'test', null, null, '0', '2017-11-06 10:20:36');
INSERT INTO `sys_user` VALUES ('1709067GM45GAF5P', 'jack', 'afee05e30d029ac3b61a2dc6c08d7b27', 'jack', '22', '0', '3', null, '上海市', '上海市市轄區(qū)', '靜安區(qū)', '上海老薛', 'abcd', null, null, '0', '2017-09-06 10:35:28');
INSERT INTO `sys_user` VALUES ('170908G65M59XWH0', 'test003', 'afee05e30d029ac3b61a2dc6c08d7b27', 'test003', '20', '0', '3', null, '上海市', '上海市市轄區(qū)', '黃浦區(qū)', '老薛家', 'tx5D', null, null, '1', '2017-09-08 21:19:40');
INSERT INTO `sys_user` VALUES ('170918GDXW2DNP4H', 'test001', 'afee05e30d029ac3b61a2dc6c08d7b27', 'test0016', '18', '1', '9', null, '湖北省', '鄂州市', '華容區(qū)', '123', 'W5k4', null, null, '0', '2017-09-18 21:42:51');
INSERT INTO `sys_user` VALUES ('171020FWN55RS5AW', 'test1001', '75a5298456daeb532320fdd4a9eacec0', 'test1001', null, null, null, null, null, null, null, null, '3883', null, null, '0', '2017-10-20 20:51:05');
INSERT INTO `sys_user` VALUES ('1803269654BP2428', 'imoocMon Mar 26 12:55:11 CST 2018', 'abc123', 'imoocMon Mar 26 12:55:11 CST 2018', null, null, null, null, null, null, null, null, null, null, null, '0', '2018-03-26 12:55:11');
-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`sys_user_id` varchar(20) NOT NULL,
`sys_role_id` int(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ('21', '1709067GM45GAF5P', '1');
-- ----------------------------
-- Table structure for t_test
-- ----------------------------
DROP TABLE IF EXISTS `t_test`;
CREATE TABLE `t_test` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of t_test
-- ----------------------------
INSERT INTO `t_test` VALUES ('1', '111');
INSERT INTO `t_test` VALUES ('2', '222');
INSERT INTO `t_test` VALUES ('3', '333');
使用generatorConfig生成mapper以及pojo
- 使用generatorConfig生成mapper以及pojo
- 實現(xiàn)基于mybatis的CRUD功能 ---增刪改查
- 整合mybatis-pagehelper實現(xiàn)分頁
- 自定義mapper的實現(xiàn)
#github的項目
https://github.com/leechenxiang/imooc-springboot-starter
#Spring Boot 集成 MyBatis--開源框架 (分頁插件 PageHelper, 通用 Mapper)
https://github.com/abel533/MyBatis-Spring-Boot
#PageHelper-Spring-Boot-Starter 幫助你集成分頁插件到 Spring Boot帆竹。
https://github.com/pagehelper/pagehelper-spring-boot
根據(jù)MyBatis-Spring-Boot說明在pom.xml中引入依賴包
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.2.4</version>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
在pom.xml中引入阿里的druid及mysql-connector-java
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<!-- 引入 redis 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application.properties配置(生成環(huán)境可以不需要,主要時熱部署功能)
#https://github.com/abel533/MyBatis-Spring-Boot 為mybatis設(shè)置合砂,生成環(huán)境可以刪除
restart.include.mapper=/mapper-[\\w-\\.]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar
利用MyBatis生成器自動生成實體類、DAO接口和Mapping映射文件
參考文章
利用MyBatis生成器自動生成實體類锯七、DAO接口和Mapping映射文件
使用Mybatis-Generator自動生成Dao链快、Model、Mapping相關(guān)文件(轉(zhuǎn))
mybatis-generator自動生成代碼插件使用詳解
mybatis-generator插件自動生成實體代碼
MyBatis使用過程中踩過的坑--Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli)
Unexpected error while running MyBatis Generator. Exception getting JDBC Driver
application.properties 配置數(shù)據(jù)源
#####################################################
#
#配置數(shù)據(jù)源相關(guān)眉尸,使用阿里巴巴的druid數(shù)據(jù)源
#存儲到數(shù)據(jù)庫中文亂碼問題
#spring.datasource.url=jdbc:mysql://39.97.171.163:3306/wechatTaskDb?useUnicode=true&&characterEncoding=UTF-8&autoReconnect=true
#
#####################################################
#spring.datasource.url=jdbc:mysql://localhost:3306/leecx
spring.datasource.url=jdbc:mysql://39.97.171.***:3306/leecx
spring.datasource.username=root
#mysql數(shù)據(jù)root用戶密碼
spring.datasource.password=root的密碼
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true
application.properties 配置--mybatis
#####################################################
#
#mybatis配置(按官網(wǎng))
#
#####################################################
#mybatis
#mybatis.type-aliases-package=tk.mybatis.springboot.model 這是mybatis生成model或pojo路徑
mybatis.type-aliases-package=com.younghare.pojo
#在classpath目錄下建立一個mapper文件夾域蜗,這個文件夾下將會生成一些xml文件
mybatis.mapper-locations=classpath:mapper/*.xml
#通用mapper 的配置
#mappers 多個接口時逗號隔開
#mapper.mappers=tk.mybatis.springboot.util.MyMapper
mapper.mappers=com.younghare.util.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL
#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
創(chuàng)建MyMapper.java類,路徑與application.properties中配置一致
/**
* 繼承自己的MyMapper
*/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
//TODO
//FIXME 特別注意噪猾,該接口不能被掃描到霉祸,否則會出錯
}
添加generatorConfig.xml (利用idea的插件生成,所有直接放在resouces)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.younghare.util.MyMapper"/>
</plugin>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://39.97.***.1**:3306/leecx"
userId="root"
password="mysql root用戶密碼">
</jdbcConnection>
<!-- 對于生成的pojo所在包 -->
<javaModelGenerator targetPackage="com.younghare.pojo" targetProject="src/main/java"/>
<!-- 對于生成的mapper所在目錄 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!-- 配置mapper對應(yīng)的java映射 -->
<javaClientGenerator targetPackage="com.younghare.mapper" targetProject="src/main/java"
type="XMLMAPPER"/>
<table tableName="sys_user"></table>
</context>
</generatorConfiguration>
配置pom.xml 添加MyBatis Generator 插件袱蜡,用于數(shù)據(jù)庫逆向生成Dao丝蹭、Model、Mapping相關(guān)文件
<plugins>
....
<!--添加mybatis的generator 插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<!--1.3.2好像不行-->
<version>1.3.2</version>
<configuration>
<!-- mybatis用于生成代碼的配置文件-->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<!--MyBatis Generator及工具-->
<!--Cannot instantiate object of type tk.mybatis.mapper.generator.MapperPlugin-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--原來版本:5.1.41-->
<!--https://www.cnblogs.com/SacredOdysseyHD/p/8460644.html-->
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.6</version>
</dependency>
</dependencies>
</plugin>
</plugins>
***標(biāo)注2位置的2個jar其實不需要
利用Idea的mybatis-generator自動生成
到generatorConfig.xml的對應(yīng)行中看看哪里出錯了
到這里先把工程做個備份
https://yunpan.#/surl_yLfjj3QXt8s (提取碼:c822)
實現(xiàn)基于mybatis接口實現(xiàn)增刪改查(CRUD)功能
引用推特的id生成器idworker
copy idworker 包到工程的java目錄
在Applicaiton類添加mybatis mapper的包掃描路徑
Sid需要添加@Component注解
創(chuàng)建SysUserMapperCustom.java(自定義xml 的sql腳本要用 坪蚁。后面采用到奔穿,這里先加進(jìn)來)
public interface SysUserMapperCustom {
List<SysUser> queryUserSimplyInfoById(String id);
}
添加UserService及其實現(xiàn)類UserServiceImpl
創(chuàng)建service目錄和service.impl目錄
userMapper提供的很多方法是哪里來的????????好像是來自Mapper代理實現(xiàn)
創(chuàng)建MyBatisCRUDController.java
運行項目敏晤,并訪問保存用戶
#保存用戶
http://localhost:8080/mybatis/saveUser
問題一 :奇葩提示 (這個好像不要管):關(guān)于無法注入或注入失敗的問題Could not autowire field || BeanCreationException
該問題的解決辦法參見:mybatis+spring boot, mapper 提示Could not autowire. No beans of … type found
我采用: @Autowired (required = false)
問題二:運行后提示信息:
nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseInsertProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseInsertProvider
tk.mapper(通用mapper)出現(xiàn)的問題:Error invoking SqlProvider method
問題二的解決:MapperScan包引用替換
#更新sys_user表用戶id = 10011001 的記錄
http://localhost:8080/mybatis/updateUser
整合MyBatis - 使用pagehelper實現(xiàn)分頁(mybatis-pagehelper)
@Override
@Transactional(propagation = Propagation.SUPPORTS) //查詢分頁:第幾頁贱田;每頁幾條記錄
public List<SysUser> queryUserListPaged(SysUser user, Integer page, Integer pageSize) {
// 開始分頁
PageHelper.startPage(page, pageSize); //設(shè)置分頁回對sql語句進(jìn)行攔截包裝 分頁
Example example = new Example(SysUser.class);
Example.Criteria criteria = example.createCriteria();
if (!StringUtils.isEmptyOrWhitespace(user.getNickname())) {
criteria.andLike("nickname", "%" + user.getNickname() + "%");
}
example.orderBy("registTime").desc();//排序
List<SysUser> userList = userMapper.selectByExample(example);
return userList;
}
#分頁查詢,默認(rèn)查詢第一頁嘴脾,或小于1時男摧,返回第一頁
http://localhost:8080/mybatis/queryUserListPaged
#查詢第二頁,如果頁碼超過實際的頁數(shù)译打,則返回最后一頁
http://localhost:8080/mybatis/queryUserListPaged?page=2
整合MyBatis - 自定義mapper的實現(xiàn)
運用場景是需要自己寫sql語句彩倚,比如多表關(guān)聯(lián),此時我們就需要用到自定義mapper
自定義mapper就是前面用到的SysUserMapperCustom.java
定義自定義mapper的xml放在資源中SysUserMapperCustom.xml
<?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="com.younghare.mapper.SysUserMapperCustom" >
<!-- 查詢簡單的用戶信息 -->
<select id="queryUserSimplyInfoById" resultType="com.younghare.pojo.SysUser"
parameterType="java.lang.String" >
select
*
from
sys_user
where
id = #{id,jdbcType=VARCHAR}
</select>
</mapper>
需要在UserServiceImpl注入和實現(xiàn)邏輯
#自定義mapper查詢扶平,默認(rèn)查詢第一頁,或小于1時蔬蕊,返回第一頁(注意參數(shù)中不能含有空格)
http://localhost:8080/mybatis/queryUserByIdCustom?userId=10011001
整合MyBatis - 引入事務(wù)執(zhí)行回滾
事務(wù)的隔離級別&事務(wù)的傳播行為
Spring事務(wù)隔離級別和傳播特性
在UserServiceImpl中模擬一個異常
@Override
@Transactional(propagation = Propagation.REQUIRED) //=====這里時對事務(wù)的注解结澄,沒用這個注解時,會插入數(shù)據(jù)岸夯,有注解時麻献,則會處理回滾
public void saveUserTransactional(SysUser user) {
userMapper.insert(user);
int a = 1 / 0; //模擬異常
user.setIsDelete(1);
userMapper.updateByPrimaryKeySelective(user);
}
MyBatisCRUDController.java中添加
@RequestMapping("/saveUserTransactional")
public IYounghareJSONResult saveUserTransactional() {
String userId = sid.nextShort();
SysUser user = new SysUser();
user.setId(userId);
user.setUsername("lee" + new Date());
user.setNickname("lee除零錯誤是否" + new Date());
user.setPassword("abc123");
user.setIsDelete(0);
user.setRegistTime(new Date());
userService.saveUserTransactional(user);
return IYounghareJSONResult.ok("保存成功");
}
#自定義mapper查詢,默認(rèn)查詢第一頁猜扮,或小于1時勉吻,返回第一頁(注意參數(shù)中不能含有空格)
http://localhost:8080/mybatis/saveUserTransactional
除零異常,但記錄已經(jīng)插入到數(shù)據(jù)庫
到這里先把工程做個備份
https://yunpan.#/surl_yLKuS7x6Ced (提取碼:7774)