Mybatis-Plus入门(一)
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
本章主要针对Mybatis-plus学习的小白入门教程,能够快速上手使用,前置知识,JDBC,MySQL,SpringBoot工程的搭建
一、Mybatis-Plus是什么?
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生,作为一个持久层的框架,它能够实现低sql的持久层开发,提升开发效率。
MyBatis-Plus所期望的愿景是:
我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
如图所示:
MyBatis-Plus的代码托管地址如下所示:
官网:http://mp.baomidou.com
码云: https://gitee.com/baomidou/mybatis-plus
Github: https://github.com/baomidou/mybatis-plus
二、环境搭建
1.新建一个简单的springboot项目
打开IDEA,点击新建项目,直接上图
配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tiezhu</groupId>
<artifactId>mybatisplus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisplus</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.建立数据库
平常使用的是Navicat工具进行MySQL数据库的链接和操作,新建一个名为mybatis-plus的数据库,然后建立一个名为user的表。
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`password` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
3.修改配置文件
在application.properties中进行如下配置
server.port=8010 #服务启动端口
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8&useSSL=true #数据库链接
spring.datasource.username=root #数据库用户名
spring.datasource.password=123456 #数据库密码
二.简单增删改查操作
1.建立user实体类和Mapper层
在src下main的java文件夹中新建以下文件夹
实体类中会用到lombok插件,不了解的朋友可以看这篇帖子:
lombok
新建user类,属性和数据库中一一对应
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private String password;
private Integer age;
private String email;
}
在mapper文件夹当中新建interface类型的UserMapper文件,并且继承BaseMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tiezhu.mybatisplus.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
2.插入数据操作
在一切准备好之后,我们可以先测试一下JDBC是否链接成功,在test文件夹中新建
UserMapperTest文件。
在数据库中随便添加一条数据,然后在新建的UserMapperTest文件当中加入以下代码:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiezhu.mybatisplus.entity.User;
import com.tiezhu.mybatisplus.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
@SpringBootTest
public class UserMapperTest {
@Resource
private UserMapper userMapper;
@Test
public void testConnection() throws SQLException {
List<User> userList = userMapper.selectList(new QueryWrapper<User>());
userList.forEach(System.out::println);
}
}
当查询到前面在数据库中添加的数据时,即代表我们前面配置的所有步骤成功。
在utils文件夹中新建一个RandomUtil文件用以生成随机数据:
import java.util.Random;
public class RandomUtil {
static Random random = new Random();
public static String getName(){//随机姓名
String[] Surname = {"赵","钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
"何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎",
"鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷",
"罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和",
"穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒",
"屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季"};
String girl = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽 ";
String boy = "伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";
int index = random.nextInt(Surname.length - 1);
String name = Surname[index]; //获得一个随机的姓氏
int i = random.nextInt(3);//可以根据这个数设置产生的男女比例
if(i==2){
int j = random.nextInt(girl.length()-2);
if (j % 2 == 0) {
name = name + girl.substring(j, j + 2);
} else {
name = name + girl.substring(j, j + 1);
}
}
else{
int j = random.nextInt(girl.length()-2);
if (j % 2 == 0) {
name = name + boy.substring(j, j + 2);
} else {
name = name + boy.substring(j, j + 1);
}
}
return name;
}
public static String getEmail(){//随机邮箱
String email="";
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char[] chars=str.toCharArray();
String[] end={"@qq.com","@163.com"};
for (int i = 0; i <10 ; i++) {
email+=chars[random.nextInt(61)];
}
email+=end[random.nextInt(2)];
return email;
}
public static String getPwd(){//随机密码
String pwd="";
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char[] chars=str.toCharArray();
for (int i = 0; i <6 ; i++) {
pwd+=chars[random.nextInt(61)];
}
return pwd;
}
}
插10条数据:
@Test
public void testInsertDate(){
List<User> userList=new ArrayList<>();
int count=0;
for (int i = 0; i <10 ; i++) {
count+= userMapper.insert(new User(null, RandomUtil.getName(), RandomUtil.getPwd(),
new Random().nextInt(30) + 10, RandomUtil.getEmail()));
}
if (count!=0){
System.out.println("插入了"+count+"条数据");
}else System.out.println("插入失败");
}
3.修改数据
将id为2的用户的邮箱修改为188741741@qq.com
@Test
public void testUpDate(){
User user=new User();
user.setId(2L);
user.setEmail("188741741@qq.com");
int count = userMapper.updateById(user);
if (count!=0){
System.out.println("修改了"+count+"条数据");
}else System.out.println("修改失败");
}
4.查询数据
4.1按id查询
查询id为3的用户:
@Test
public void testSelectById(){
User user = userMapper.selectById(3L);
if (user!=null){
System.out.println(user.toString());
}else System.out.println("查询失败");
}
4.2列表查询
@Test
public void testSelectList(){
List<User> userList = userMapper.selectList(new QueryWrapper<User>());
userList.forEach(System.out::println);
}
5.删除数据
删除id为1的数据。
@Test
public void testDelete(){
int i = userMapper.deleteById(1L);
if (i!=0){
System.out.println("删除了"+i+"条数据");
}else System.out.println("删除失败");
}
6.MybatisPlus日志配置
配置日志能够看到MybatisPlus在运行时的sql语句,在application.properties中加入如下代码:
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
选择一个test方法运行
总结
MybatisPlus是对Mybatis的升级优化,并不是替代,原有的Mybatis代码仍然可使用,下期预告:MybatisPlus的条件操作和IService。