前言
https://yunpan.360.cn/surl_yLKZ52FG45K (提取码:1a6e)
涉及到的知识点
- 用navicat创建mysq数据库及表结构
- Spring-Boot整合--MyBatis
- Spring-Boot整合--阿里druid数据库连接池
- Spring-Boot整合--mysql-connector
- 在idea开发环境中利用MyBatis Generator 插件,用于数据库逆向生成Dao、Model、Mapping相关文件
- tk.mybatis.mapper 第三方通用mapper https://github.com/abel533/MyBatis-Spring-Boot
- 推特的id生成器idworker
- pageHelper插件
- 自定义mapper
- mybatis ---事务处理
- IntelliJ IDEA 连接数据库 详细过程
- Spring Boot中使用MyBatis注解配置详解-今日头条
8 Springboot整合MyBatis
用Navicat创建mysql数据库 leecx
并执行sql脚本leecx.sql,执行后的
执行leecx.sql脚本之后情况---ER图 执行leecx.sql脚本之后情况
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 '数据字典类型名称',
`type_code` varchar(64) DEFAULT NULL COMMENT '数据字典类型代码',
`ddkey` varchar(6) NOT NULL COMMENT '数据键',
`ddvalue` varchar(12) NOT NULL COMMENT '数据值',
`is_show` int(1) NOT NULL COMMENT '是否显示,1:显示;2:不显示',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COMMENT='数据字典表';
-- ----------------------------
-- 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', '职业', 'job', '1', 'Java开发', '1');
INSERT INTO `data_dict` VALUES ('7', '职业', 'job', '2', '前端开发', '1');
INSERT INTO `data_dict` VALUES ('8', '职业', 'job', '3', '大数据开发', '1');
INSERT INTO `data_dict` VALUES ('9', '职业', 'job', '4', 'ios开发', '1');
INSERT INTO `data_dict` VALUES ('10', '职业', 'job', '5', 'Android开发', '1');
INSERT INTO `data_dict` VALUES ('11', '职业', 'job', '6', 'Linux系统工程师', '1');
INSERT INTO `data_dict` VALUES ('12', '职业', 'job', '7', 'PHP开发', '1');
INSERT INTO `data_dict` VALUES ('13', '职业', 'job', '8', '.net开发', '1');
INSERT INTO `data_dict` VALUES ('14', '职业', 'job', '9', 'C/C++', '1');
INSERT INTO `data_dict` VALUES ('15', '职业', 'job', '10', '学生', '0');
INSERT INTO `data_dict` VALUES ('16', '职业', 'job', '11', '其它', '1');
INSERT INTO `data_dict` VALUES ('17', '职业', 'job', '12', '全栈牛逼架构师', '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', '天木兰 经典 船鞋', '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:顶级根权限\r\n1:菜单,间接代表就是 isParent=true\r\n2:普通链接(按钮,link等)',
`url` varchar(128) DEFAULT NULL COMMENT '访问url地址',
`percode` varchar(128) DEFAULT NULL COMMENT '权限代码字符串',
`parentid` int(11) DEFAULT NULL COMMENT '父结点id\r\n为0代表根节点',
`parentids` varchar(128) DEFAULT NULL COMMENT '父结点id列表串',
`sort` int(3) DEFAULT NULL COMMENT '排序号',
`available` int(1) NOT NULL COMMENT '是否可用,1:可用,0不可用',
`description` varchar(128) DEFAULT NULL COMMENT '当前资源描述',
`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', '企业会员', '1', '/company/mng', 'company:mng', '216', null, null, '1', '会员管理 - 企业会员', '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', '会员管理 - 企业会员 下查看资源', '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', '会员管理 - 企业会员', '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', '会员管理 - 企业会员', '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', '总经理', '1');
INSERT INTO `sys_role` VALUES ('3', '客服', '1');
INSERT INTO `sys_role` VALUES ('4', '销售/市场专员', '1');
INSERT INTO `sys_role` VALUES ('5', '产品团队', '1');
INSERT INTO `sys_role` VALUES ('6', '技术团队', '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 '权限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:男\r\n2:保密 ',
`job` int(10) DEFAULT NULL COMMENT '职业类型:\r\n1:Java开发\r\n2:前端开发\r\n3:大数据开发\r\n4:ios开发\r\n5:Android开发\r\n6:Linux系统工程师\r\n7:PHP开发\r\n8:.net开发\r\n9:C/C++\r\n10:学生\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 '区',
`address` varchar(128) DEFAULT NULL COMMENT '详细地址',
`auth_salt` varchar(16) DEFAULT NULL COMMENT '用于权限的“盐”',
`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='系统后台用户';
-- ----------------------------
-- 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, '上海市', '上海市市辖区', '静安区', '上海老薛', 'abcd', null, null, '0', '2017-09-06 10:35:28');
INSERT INTO `sys_user` VALUES ('170908G65M59XWH0', 'test003', 'afee05e30d029ac3b61a2dc6c08d7b27', 'test003', '20', '0', '3', null, '上海市', '上海市市辖区', '黄浦区', '老薛家', 'tx5D', null, null, '1', '2017-09-08 21:19:40');
INSERT INTO `sys_user` VALUES ('170918GDXW2DNP4H', 'test001', 'afee05e30d029ac3b61a2dc6c08d7b27', 'test0016', '18', '1', '9', null, '湖北省', '鄂州市', '华容区', '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
- 实现基于mybatis的CRUD功能 ---增删改查
- 整合mybatis-pagehelper实现分页
- 自定义mapper的实现
#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
根据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配置(生成环境可以不需要,主要时热部署功能)
#https://github.com/abel533/MyBatis-Spring-Boot 为mybatis设置,生成环境可以删除
restart.include.mapper=/mapper-[\\w-\\.]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar
利用MyBatis生成器自动生成实体类、DAO接口和Mapping映射文件
参考文章
利用MyBatis生成器自动生成实体类、DAO接口和Mapping映射文件
使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件(转)
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 配置数据源
#####################################################
#
#配置数据源相关,使用阿里巴巴的druid数据源
#存储到数据库中文乱码问题
#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数据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配置(按官网)
#
#####################################################
#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
创建MyMapper.java类,路径与application.properties中配置一致
/**
* 继承自己的MyMapper
*/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
//TODO
//FIXME 特别注意,该接口不能被扫描到,否则会出错
}
MyMapper.java存放路径
添加generatorConfig.xml (利用idea的插件生成,所有直接放在resouces)
generatorConfig.xml<?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对应的java映射 -->
<javaClientGenerator targetPackage="com.younghare.mapper" targetProject="src/main/java"
type="XMLMAPPER"/>
<table tableName="sys_user"></table>
</context>
</generatorConfiguration>
配置pom.xml 添加MyBatis Generator 插件,用于数据库逆向生成Dao、Model、Mapping相关文件
<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>
generatorConfig.xml位置及mysql和generator.jar
***标注2位置的2个jar其实不需要
利用Idea的mybatis-generator自动生成
利用Idea的mybatis-generator自动生成 XMLParserException: XML Parser Error on line 14: 元素类型为 "plugin" 的内容必须匹配 "(property)到generatorConfig.xml的对应行中看看哪里出错了
到这里先把工程做个备份
https://yunpan.360.cn/surl_yLfjj3QXt8s (提取码:c822)
实现基于mybatis接口实现增删改查(CRUD)功能
引用推特的id生成器idworker
copy idworker 包到工程的java目录
在Applicaiton类添加mybatis mapper的包扫描路径
在Applicaiton类添加mybatis包路径的配置Sid需要添加@Component注解
Sid需要添加@Component注解
创建SysUserMapperCustom.java(自定义xml 的sql脚本要用 。后面采用到,这里先加进来)
public interface SysUserMapperCustom {
List<SysUser> queryUserSimplyInfoById(String id);
}
添加UserService及其实现类UserServiceImpl
创建service目录和service.impl目录
创建目录、servie及service.impl目录
userMapper提供的很多方法是哪里来的????????好像是来自Mapper代理实现
userMapper提供的很多方法是哪里来的 tk中为我们实现
创建MyBatisCRUDController.java
运行项目,并访问保存用户
#保存用户
http://localhost:8080/mybatis/saveUser
问题一 :奇葩提示 (这个好像不要管):关于无法注入或注入失败的问题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
image.png
tk.mapper(通用mapper)出现的问题:Error invoking SqlProvider method
问题二的解决:MapperScan包引用替换
MapperScan包引用替换#更新sys_user表用户id = 10011001 的记录
http://localhost:8080/mybatis/updateUser
整合MyBatis - 使用pagehelper实现分页(mybatis-pagehelper)
@Override
@Transactional(propagation = Propagation.SUPPORTS) //查询分页:第几页;每页几条记录
public List<SysUser> queryUserListPaged(SysUser user, Integer page, Integer pageSize) {
// 开始分页
PageHelper.startPage(page, pageSize); //设置分页回对sql语句进行拦截包装 分页
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;
}
PageHelper使用
#分页查询,默认查询第一页,或小于1时,返回第一页
http://localhost:8080/mybatis/queryUserListPaged
#查询第二页,如果页码超过实际的页数,则返回最后一页
http://localhost:8080/mybatis/queryUserListPaged?page=2
默认查询第一页的结果
整合MyBatis - 自定义mapper的实现
运用场景是需要自己写sql语句,比如多表关联,此时我们就需要用到自定义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注入和实现逻辑
自定义mapper的xml
#自定义mapper查询,默认查询第一页,或小于1时,返回第一页(注意参数中不能含有空格)
http://localhost:8080/mybatis/queryUserByIdCustom?userId=10011001
自定义mapper查询结果
整合MyBatis - 引入事务执行回滚
事务的隔离级别&事务的传播行为
Spring事务隔离级别和传播特性
在UserServiceImpl中模拟一个异常
@Override
@Transactional(propagation = Propagation.REQUIRED) //=====这里时对事务的注解,没用这个注解时,会插入数据,有注解时,则会处理回滚
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查询,默认查询第一页,或小于1时,返回第一页(注意参数中不能含有空格)
http://localhost:8080/mybatis/saveUserTransactional
除零异常,但记录已经插入到数据库
除零异常 没用采用事务会插入数据
到这里先把工程做个备份
https://yunpan.360.cn/surl_yLKuS7x6Ced (提取码:7774)
网友评论