视频地址:【尚硅谷】MyBatisPlus教程(一套玩转mybatis-plus)_哔哩哔哩_bilibili
- 尚硅谷MyBatis-Plus笔记01【简介、入门案例、基本CRUD】
尚硅谷MyBatis-Plus笔记02【】
尚硅谷MyBatis-Plus笔记03【】
尚硅谷MyBatis-Plus笔记04【】
尚硅谷MyBatis-Plus笔记05【】
目录
P03【03-MyBatis-Plus支持的数据库以及框架结构】03:00
P07【07-配置application.yml】08:16
P08【08-创建实体类以及lombok的简单使用】05:53
P13【13-测试BaseMapper的新增功能】04:25
P14【14-测试BaseMapper的删除功能】08:22
P15【15-测试BaseMapper的修改功能】03:08
P16【16-测试BaseMapper的查询功能】07:36
P19【19-测试通用Service之查询总记录数】03:13
P20【20-测试通用Service之批量添加功能】06:28
P21【21-MyBatis-Plus的常用注解@TableName】06:14
MyBatis-Plus是MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。本视频从MyBatis-Plus的特性到优秀插件,以及多数据源的配置都有详细讲解。
尚硅谷 MyBatis-Plus,讲师:杨博超
课程主要内容
MyBatis-plus官网:MyBatis-Plus
版本:
- IDE:idea 2019.2
- JDK:JDK8+
- 构建工具:maven 3.5.4
- MySQL版本:MySQL 5.7
- Spring Boot:2.6.3
- MyBatis-Plus:3.5.1
bigint而不是int,MyBatisPlus进行数据插入的时候默认使用雪花算法来生成id,长度比较长,所以使用bigint。
- CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
- USE `mybatis_plus`;
- CREATE TABLE `user` (
- `id` BIGINT(20) NOT NULL COMMENT '主键ID',
- `name` VARCHAR(30) DEFAULT NULL COMMENT '姓名',
- `age` INT(11) DEFAULT NULL COMMENT '年龄',
- `email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
- PRIMARY KEY (`id`)
- ) ENGINE=INNODB DEFAULT CHARSET=utf8;
-
- INSERT INTO USER (id, NAME, age, email) VALUES
- (1, 'Jone', 18, 'test1@baomidou.com'),
- (2, 'Jack', 20, 'test2@baomidou.com'),
- (3, 'Tom', 28, 'test3@baomidou.com'),
- (4, 'Sandy', 21, 'test4@baomidou.com'),
- (5, 'Billie', 24, 'test5@baomidou.com');
- "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.0modelVersion>
- <parent>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-parentartifactId>
- <version>2.6.3version>
- <relativePath/>
- parent>
- <groupId>com.atguigugroupId>
- <artifactId>mybatisplusartifactId>
- <version>0.0.1-SNAPSHOTversion>
- <name>mybatisplusname>
- <description>mybatisplusdescription>
- <properties>
- <java.version>1.8java.version>
- properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starterartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
-
-
- <dependency>
- <groupId>com.baomidougroupId>
- <artifactId>mybatis-plus-boot-starterartifactId>
- <version>3.5.1version>
- dependency>
-
-
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
-
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <scope>runtimescope>
- dependency>
-
-
- dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-maven-pluginartifactId>
- plugin>
- plugins>
- build>
-
- project>
- application.properties
-
- #spring.datasource.type=com.zaxxer.hikari.HikariDataSource
- #spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- application.yml
-
- spring:
- # 配置数据源信息
- datasource:
- # 配置数据源类型
- type: com.zaxxer.hikari.HikariDataSource
- # 配置连接数据库信息
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf8&useSSL=false
- username: root
- password: 123456
Data注解:相当于无参构造、getter、setter、equals、hashCode、toString方法。
- BaseMapper是MyBatis-Plus提供的模板mapper,其中包含了基本的CRUD方法,泛型为操作的实体类型。
- @MapperScan("com.atguigu.mybatisplus.mapper") //用于扫描mapper接口所在的包、扫描指定包下面的mapper接口
IDEA在 userMapper 处报错,因为找不到注入的对象,因为类是动态创建的,但是程序可以正确地执行。
为了避免报错,可以在mapper接口上添加 @Repository 注解。
- package com.atguigu.mybatisplus;
-
- import com.atguigu.mybatisplus.mapper.UserMapper;
- import com.atguigu.mybatisplus.pojo.User;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import java.util.List;
-
- @SpringBootTest
- public class MybatisPlusTest {
- @Autowired
- private UserMapper userMapper;//正常报错,不影响运行
- //userMapper动态生成的代理类交给了ioc容器管理
-
- @Test
- public void testSelectList() {
- //通过条件构造器查询一个list集合,若没有条件,则可以设置null为参数.
- List
list = userMapper.selectList(null); - list.forEach(System.out::println);
- }
- }
BaseMapper.java,MyBatis-Plus中的基本CRUD在内置的BaseMapper中都已得到了实现,我们可以直接使用,接口如 下:
- /*
- * Copyright (c) 2011-2022, baomidou (jobob@qq.com).
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package com.baomidou.mybatisplus.core.mapper;
-
- import com.baomidou.mybatisplus.core.conditions.Wrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
- import com.baomidou.mybatisplus.core.toolkit.Constants;
- import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
- import org.apache.ibatis.annotations.Param;
-
- import java.io.Serializable;
- import java.util.Collection;
- import java.util.List;
- import java.util.Map;
-
- /*
- _ _ /_ _ _/_. ____ / _
- / / //_//_//_|/ /_\ /_///_/_\ Talk is cheap. Show me the code.
- _/ /
- */
-
- /**
- * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
- *
这个 Mapper 支持 id 泛型
- *
- * @author hubin
- * @since 2016-01-23
- */
- public interface BaseMapper
extends Mapper { - /**
- * 插入一条记录
- *
- * @param entity 实体对象
- */
- int insert(T entity);
-
- /**
- * 根据 ID 删除
- *
- * @param id 主键ID
- */
- int deleteById(Serializable id);
-
- /**
- * 根据实体(ID)删除
- *
- * @param entity 实体对象
- * @since 3.4.4
- */
- int deleteById(T entity);
-
- /**
- * 根据 columnMap 条件,删除记录
- *
- * @param columnMap 表字段 map 对象
- */
- int deleteByMap(@Param(Constants.COLUMN_MAP) Map
columnMap) ; -
- /**
- * 根据 entity 条件,删除记录
- *
- * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
- */
- int delete(@Param(Constants.WRAPPER) Wrapper
queryWrapper) ; -
- /**
- * 删除(根据ID或实体 批量删除)
- *
- * @param idList 主键ID列表或实体列表(不能为 null 以及 empty)
- */
- int deleteBatchIds(@Param(Constants.COLLECTION) Collection> idList);
-
- /**
- * 根据 ID 修改
- *
- * @param entity 实体对象
- */
- int updateById(@Param(Constants.ENTITY) T entity);
-
- /**
- * 根据 whereEntity 条件,更新记录
- *
- * @param entity 实体对象 (set 条件值,可以为 null)
- * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
- */
- int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper
updateWrapper) ; -
- /**
- * 根据 ID 查询
- *
- * @param id 主键ID
- */
- T selectById(Serializable id);
-
- /**
- * 查询(根据ID 批量查询)
- *
- * @param idList 主键ID列表(不能为 null 以及 empty)
- */
- List
selectBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList); -
- /**
- * 查询(根据 columnMap 条件)
- *
- * @param columnMap 表字段 map 对象
- */
- List
selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap) ; -
- /**
- * 根据 entity 条件,查询一条记录
- *
查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常
- *
- * @param queryWrapper 实体对象封装操作类(可以为 null)
- */
- default T selectOne(@Param(Constants.WRAPPER) Wrapper
queryWrapper) { - List
ts = this.selectList(queryWrapper); - if (CollectionUtils.isNotEmpty(ts)) {
- if (ts.size() != 1) {
- throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
- }
- return ts.get(0);
- }
- return null;
- }
-
- /**
- * 根据 Wrapper 条件,判断是否存在记录
- *
- * @param queryWrapper 实体对象封装操作类
- * @return
- */
- default boolean exists(Wrapper
queryWrapper) { - Long count = this.selectCount(queryWrapper);
- return null != count && count > 0;
- }
-
- /**
- * 根据 Wrapper 条件,查询总记录数
- *
- * @param queryWrapper 实体对象封装操作类(可以为 null)
- */
- Long selectCount(@Param(Constants.WRAPPER) Wrapper
queryWrapper) ; -
- /**
- * 根据 entity 条件,查询全部记录
- *
- * @param queryWrapper 实体对象封装操作类(可以为 null)
- */
- List
selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper) ; -
- /**
- * 根据 Wrapper 条件,查询全部记录
- *
- * @param queryWrapper 实体对象封装操作类(可以为 null)
- */
- List
-
- /**
- * 根据 Wrapper 条件,查询全部记录
- *
注意: 只返回第一个字段的值
- *
- * @param queryWrapper 实体对象封装操作类(可以为 null)
- */
- List
-
- /**
- * 根据 entity 条件,查询全部记录(并翻页)
- *
- * @param page 分页查询条件(可以为 RowBounds.DEFAULT)
- * @param queryWrapper 实体对象封装操作类(可以为 null)
- */
-
extends IPage> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper queryWrapper) ;
-
- /**
- * 根据 Wrapper 条件,查询全部记录(并翻页)
- *
- * @param page 分页查询条件
- * @param queryWrapper 实体对象封装操作类
- */
-
extends IPage
- }
- @Test
- public void testInsert() {
- //实现新增用户信息
- //INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
- User user = new User();
- //user.setId(100L);
- user.setName("张三");
- user.setAge(23);
- user.setEmail("zhangsan@atguigu.com");
- int result = userMapper.insert(user);
- System.out.println("result:" + result);
- System.out.println("id:" + user.getId());
- }
- @Test
- public void testDelete() {
- //1、通过id删除用户信息
- //DELETE FROM user WHERE id=?
- // int result = userMapper.deleteById(1659014646172069890L);
- // System.out.println("result:" + result);
-
- //2、根据map集合中所设置的条件删除用户信息
- //DELETE FROM user WHERE name = ? AND age = ?
- // Map
map = new HashMap<>(); - // map.put("name", "张三");
- // map.put("age", 23);
- // int result = userMapper.deleteByMap(map);
- // System.out.println("result:" + result);
-
- //3、通过多个id实现批量删除
- //DELETE FROM user WHERE id IN ( ? , ? , ? )
- List
list = Arrays.asList(1L, 2L, 3L); - int result = userMapper.deleteBatchIds(list);
- System.out.println("result:" + result);
- }
- @Test
- public void testUpdate() {
- //修改用户信息
- //UPDATE user SET name=?, email=? WHERE id=?
- User user = new User();
- user.setId(4L);
- user.setName("李四");
- user.setEmail("lisi@atguigu.com");
- int result = userMapper.updateById(user);
- System.out.println("result:" + result);
- }
- @Test
- public void testSelect() {
- //通过id查询用户信息
- //SELECT id,name,age,email FROM user WHERE id=?
- User user = userMapper.selectById(1L);
- System.out.println(user);
-
- //根据多个id查询多个用户信息
- //SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
- List
list = Arrays.asList(1L, 2L, 3L); - List
users = userMapper.selectBatchIds(list); - users.forEach(System.out::println);
-
- //根据map集合中的条件查询用户信息
- //SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
- Map
map = new HashMap<>(); - map.put("name", "Jack");
- map.put("age", 20);
- List
users = userMapper.selectByMap(map); - users.forEach(System.out::println);
-
- //查询所有数据
- //SELECT id,name,age,email FROM user
- List
users = userMapper.selectList(null); - users.forEach(System.out::println);
- Map
map = userMapper.selectMapById(1L); - System.out.println(map);
- }
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.atguigu.mybatisplus.mapper.UserMapper">
-
- <select id="selectMapById" resultType="map">
- select id, name, age, email
- from user
- where id = #{id}
- select>
- mapper>
Ctrl+N:Ctrl+N按名字搜索类,搜索查看类。
- package com.atguigu.mybatisplus.service;
-
- import com.atguigu.mybatisplus.pojo.User;
- import com.baomidou.mybatisplus.extension.service.IService;
-
- public interface UserService extends IService
{ - }
- package com.atguigu.mybatisplus.service.impl;
-
- import com.atguigu.mybatisplus.mapper.UserMapper;
- import com.atguigu.mybatisplus.pojo.User;
- import com.atguigu.mybatisplus.service.UserService;
- import com.baomidou.mybatisplus.extension.service.IService;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-
- public class UserServiceImpl extends ServiceImpl
implements UserService { - }
- package com.atguigu.mybatisplus;
-
- import com.atguigu.mybatisplus.service.UserService;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- @SpringBootTest
- public class MyBatisPlusServiceTest {
-
- @Autowired
- private UserService userService;
-
- @Test
- public void testGetCount() {
- //查询总记录数
- //SELECT COUNT( * ) FROM user
- long count = userService.count();
- System.out.println("总记录数:" + count);
- }
-
- }
IDEA提供了CTRL+ALT+V对该行快速根据变量类型自动生成变量。
- package com.atguigu.mybatisplus;
-
- import com.atguigu.mybatisplus.pojo.User;
- import com.atguigu.mybatisplus.service.UserService;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import java.util.ArrayList;
- import java.util.List;
-
- @SpringBootTest
- public class MyBatisPlusServiceTest {
-
- @Autowired
- private UserService userService;
-
- @Test
- public void testGetCount() {
- //查询总记录数
- //SELECT COUNT( * ) FROM user
- long count = userService.count();
- System.out.println("总记录数:" + count);
- }
-
- @Test
- public void testInsertMore() {
- //批量添加
- //INSERT INTO user ( id, name, age ) VALUES ( ?, ?, ? )
- List
list = new ArrayList<>(); - for (int i = 1; i < 10; i++) {
- User user = new User();
- user.setId(Integer.toUnsignedLong(i * 10));
- user.setName("abc" + i);
- user.setAge(20 + i);
- list.add(user);
- }
- boolean b = userService.saveBatch(list);
- System.out.println(b);
- }
-
- }
有待学习...