Mybatis-Plus学习小项目及详细教程
Posted 浅殇忆流年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis-Plus学习小项目及详细教程相关的知识,希望对你有一定的参考价值。
Mybatis-Plus学习总结
Mybatis-plus官网:https://baomidou.com/
Mybatis-plus详细教程:https://www.hxstrive.com/subject/mybatis_plus.htm
Mybatis-plus简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
Mybatis-plus项目
- Spring Boot 2.5.0
- mybatis-plus 3.4.0
- mysql 8.0.25
- lombok
- Swagger2 2.9.2
一、准备工作
在创建项目之前,这里首先准备了一张用户信息表 user_info,相应的sql脚本如下:SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`available` int(1) NULL DEFAULT 1 COMMENT '是否可用,1 可用,0 不可用',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`deleted` int(1) NULL DEFAULT 0 COMMENT '是否删除,0 未删除, 1 删除',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像',
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
`phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号',
`salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '盐',
`sex` int(1) NULL DEFAULT NULL COMMENT '性别 0未知 1女 2男',
`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 33 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户信息表' ROW_FORMAT = Dynamic;
INSERT INTO `user_info` VALUES (1, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (2, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (3, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (4, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (5, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (6, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (7, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (8, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (9, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (10, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
SET FOREIGN_KEY_CHECKS = 1;
二、创建一个Spring Boot项目
三、添加所需依赖
在项目的pom.xml文件中添加如下依赖
<!--mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!--引入mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
四、在项目的application.yml配置文件中,配置如下信息
spring:
application:
name: mybatis-plus
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
logging:
level:
com:
example:
mybatisplus:
mapper: trace
root: warn
pattern:
console: '%p%m%n'
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
注:新建的项目默认配置文件是application.properties,在这里习惯使用yml文件格式。
.yml文件与.properties文件相互转化工具:https://www.toyaml.com/index.html
五、创建实体类
BaseEntity.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "是否删除,0 未删除, 1 删除")
@TableLogic(value = "0",delval = "1")
@TableField(value = "deleted", fill = FieldFill.INSERT)
private Integer deleted;
@ApiModelProperty(value = "是否可用,1 可用,0 不可用")
@TableField(value = "available", fill = FieldFill.INSERT)
private Integer available;
@ApiModelProperty(value = "创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "修改时间")
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
UserInfo.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("user_info") //定义表名
@ApiModel(value="UserInfo对象", description="用户信息表")
public class UserInfo extends BaseEntity {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "头像")
@TableField("avatar")
private String avatar;
@ApiModelProperty(value = "邮箱")
@TableField("email")
private String email;
@ApiModelProperty(value = "密码")
@TableField("password")
private String password;
@ApiModelProperty(value = "手机号")
@TableField("phone")
private String phone;
@ApiModelProperty(value = "盐")
@TableField("salt")
private String salt;
@ApiModelProperty(value = "性别 0未知 1女 2男")
@TableField("sex")
private Integer sex;
@ApiModelProperty(value = "姓名")
@TableField("user_name")
private String userName;
}
六、创建mapper接口
UserInfoMapper.java
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
可以明显看到,上面代码中没有自定义任何自己的方法,所有方法均从 BaseMapper 父接口继承而来。
七、添加mapper接口扫描路径配置
使用 @MapperScan 注解 在Spring Boot的启动类添加mapper接口的扫描路径配置,扫描 com.example.mybatisplus.mapper 包下面的所有 mapper!!!@SpringBootApplication
@MapperScan("com.example.mybatisplus.mapper")
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
八、编写一个简单Controller
编写一个简单的controller,使用@Autowired 注解自动注入自定义的 mapper
UserInfoController.java
@RestController
@RequestMapping("/api/userInfo")
@Api(value = "/api/userInfo", tags = {"用户信息表接口"})
public class UserInfoController {
@Autowired
private UserInfoMapper userInfoMapper;
@GetMapping
public List findAllUserList(){
List<UserInfo> list = userInfoMapper.selectList(null);
return list;
}
}
九、启动项目,进行简单测试
关于更多Mybatis-plus详细知识:
- BaseMapper 接口 CRUD
- Service CRUD 接口
- 条件构造器
- 常用注解
- 代码生成器
可以查看https://www.hxstrive.com/subject/mybatis_plus.htm
这里将不对每个知识点进行演示啦!!!
代码生成器
AutoGenerator
是 MyBatis-Plus 的代码生成器,通过 AutoGenerator
可以快速生成 Entity
、Mapper
、Mapper XML
、Service
、Controller
等各个模块的代码,极大的提升了开发效率。
代码演示
注:下面代码示例基于上面项目,所有代码在generator包下面。此外需要添加下面的依赖。
一、添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
二、编写工具类
Config.java
package com.example.generator.config;
/**
* @Author:
* @Description:
* @CreateDate: 2021-05-25 14:49
* @Version: 1.0
*/
public class Config {
public static String URL = "jdbc:mysql://127.0.0.1:3306/hang?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true";
public static String USERNAME = "root";
public static String PASSWORD = "123456";
public static String DRIVER = "com.mysql.cj.jdbc.Driver";
public static String TABLE_NAME = "sys_user,sys_role,sys_file"; //多个表明用,连接
/**
* 包名
*/
public static final String PACKAGE_PARENT = "com.example";
/**
* 文件名后缀:Dao
*/
public static final String FILE_NAME_DAO = "%sMapper";
/**
* 文件名后缀:MapperXml
*/
public static final String FILE_NAME_XML = "%sMapper";
/**
* MP开头,Service结尾
*/
public static final String FILE_NAME_SERVICE = "%sService";
/**
* 文件名后缀:ServiceImpl
*/
public static final String FILE_NAME_SERVICE_IMPL = "%sServiceImpl";
/**
* 文件名后缀:Controller
*/
public static final String FILE_NAME_CONTROLLER = "%sController";
/**
* 逻辑删除字段
*/
public static final String FIELD_LOGIC_DELETE_NAME = "deleted";
/**
* 作者
*/
public static final String AUTHOR = "generator";
/**
* 生成文件的输出目录
*/
// public static String projectPath = System.getProperty("user.dir") + "/mp-generator";
public static String projectPath = System.getProperty("user.dir");
/**
* 输出目录
*/
public static final String outputDir = projectPath + "/src/main/java";
/**
* 模板引擎。velocity / freemarker / beetl
*/
public static final String TEMPLATE_ENGINE = "freemarker";
/**
* 是否支持Swagger,默认不支持
*/
public static final Boolean SWAGGER_SUPPORT = true;
}
CommonUtils.java
package com.example.generator.utils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baom以上是关于Mybatis-Plus学习小项目及详细教程的主要内容,如果未能解决你的问题,请参考以下文章
node.js零基础详细教程:node.js操作mongodb,及操作方法的封装