P1-项目概述以及MybatisPlus使用
1.项目概述
1.1硅谷课程流程图
1.2硅谷课堂功能架构
1.3后端技术
-
SpringBoot:简化新Spring应用的初始搭建以及开发过程
-
SpringCloud:基于Spring Boot实现的云原生应用开发工具,SpringCloud使用的技术:(Spring Cloud Gateway、Spring Cloud Alibaba Nacos、Spring Cloud Alibaba Sentinel、Spring Cloud Alibaba Seata、Spring Cloud Task和Spring Cloud Feign等)
-
MyBatis-Plus:持久层框架
-
Redis:内存缓存
-
RabbitMQ:消息中间件
-
腾讯云:文件存储
-
腾讯云:视频点播
-
欢拓云直播:直播平台
-
微信支付
-
Nginx:负载均衡
-
Lombok
-
Mysql:关系型数据库
1.4前端技术
- Vue.js:web 界面的渐进式框架
- Node.js: JavaScript 运行环境
- Axios:Axios 是一个基于 promise 的 HTTP 库
- NPM:包管理器
- Babel:转码器
- Webpack:打包工具
1.5其他技术
- Docker :容器技术
- Git:代码管理工具
- DockerFile:管理Docker镜像命令文本
2.MybatisPlus入门案例
MybatisPlus单表
2.1创建数据库和数据表
创建表
CREATE TABLE USER
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
插入数据
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');
2.2创建SpringBoot工程,引入MybatisPlus依赖
创建springboot工程
引入相关依赖
<?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.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jq</groupId>
<artifactId>ggkt_mp_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ggkt_mp_demo</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>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok用来简化实体类-->
<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.3创建配置文件,启动类、实体类
-
配置文件,配置数据库驱动,连接路径,用户名,密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456
-
启动类
package com.jq.ggkt_mp_demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.jq.ggkt_mp_demo.mapper") public class GgktMpDemoApplication { public static void main(String[] args) { SpringApplication.run(GgktMpDemoApplication.class, args); } }
-
实体类
package com.jq.ggkt_mp_demo.entity; import lombok.Data; @Data public class user { private Long id; private String name; private Integer age; private String email; }
@Data的作用: 生成 以下方法
-
创建mapper接口,使用MybatisPlus
package com.jq.ggkt_mp_demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.jq.ggkt_mp_demo.entity.User; public interface UserMapper extends BaseMapper<User> { }
继承BaseMapper的原因是,BaseMapper把基本的CRUD操作方法封装好了,BaseMapper源码
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package com.baomidou.mybatisplus.core.mapper; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; public interface BaseMapper<T> extends Mapper<T> { int insert(T entity); int deleteById(Serializable id); int deleteByMap(@Param("cm") Map<String, Object> columnMap); int delete(@Param("ew") Wrapper<T> wrapper); int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList); int updateById(@Param("et") T entity); int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper); T selectById(Serializable id); List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList); List<T> selectByMap(@Param("cm") Map<String, Object> columnMap); T selectOne(@Param("ew") Wrapper<T> queryWrapper); Integer selectCount(@Param("ew") Wrapper<T> queryWrapper); List<T> selectList(@Param("ew") Wrapper<T> queryWrapper); List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper); List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper); <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper); <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper); }
3.MybatisPlus的CRUD操作
3.1添加操作
public void addUser(){
//创建User对象,设置属性值,添加到数据库
User user =new User();
user.setName("mary");
user.setAge(18);
user.setEmail("aidisheng@qq.com");
int result = userMapper.insert(user);
System.out.println(result); //影响的行数
System.out.println(user); //id自动回填
}
3.2查看sql输出日志
在配置文件中,加入响应的配置即可
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
输出日志,可以看到语句、参数、结果
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f3f0fae] was not registered for synchronization because synchronization is not active
2022-07-21 10:28:46.740 INFO 19352 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-07-21 10:28:50.685 INFO 19352 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@720638621 wrapping com.mysql.cj.jdbc.ConnectionImpl@3a175162] will not be managed by Spring
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1549944444160147457(Long), maryuup(String), 18(Integer), aidisheng@qq.com(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f3f0fae]
1
User(id=1549944444160147457, name=maryuup, age=18, email=aidisheng@qq.com)
3.3MybatisPlus主键策略
比如主键id是怎么生成的
3.3.1ID_WORKER
MyBatis-Plus默认的主键策略是:ID_WORKER 全局唯一ID
3.3.2自增策略
要想主键自增需要配置如下主键策略,需要在创建数据表的时候设置主键自增实体字段中配置 @TableId(type = IdType.AUTO)
在表对应实体类上面配置,在实体类作为主键属性上面添加注解
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
3.3.3主键策略源码分析
对于AUTO,主键id 在数据库中的设置
其它主键策略:分析 IdType 源码可知
public enum IdType {
/**
* 数据库ID自增
*/
AUTO(0),
/**
* 该类型为未设置主键类型
*/
NONE(1),
/**
* 用户输入ID
* 该类型可以通过自己注册自动填充插件进行填充
*/
INPUT(2),
/**
* 全局唯一ID
*/
ASSIGN_ID(3),
/**
* 全局唯一ID (UUID)
*/
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
3.4修改操作
修改操作: 先查,后改
// 3.修改操作 ,先查,再改
@Test
public void updateUser(){
//根据id 查询
User user = userMapper.selectById(1);
//设置修改值
user.setName("jasddddd");
//调用方法实现修改
int rows = userMapper.updateById(user);
System.out.println(rows); //影响行数
}
3.5分页查询操作
MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能
配置分页插件
package com.jq.ggkt_mp_demo.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MpConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
编写分页代码
/**
* 4.分页查询
* 创建Page对象,传递两个参数:当前页,每页显示的记录数
* 调用MybatisPlus中的方法实现分页
*/
@Test
public void findPage(){
//创建Page对象,传递两个参数:当前页,每页显示的记录数
Page<User> page =new Page<>(1,3);
//调用MybatisPlus中的方法实现分页
userMapper.selectPage(page,null);
List<User> list = page.getRecords();
System.out.println(list);//[User(id=1, name=jasddddd, age=18, email=test1@baomidou.com), User(id=2, name=Jack, age=20, email=test2@baomidou.com), User(id=3, name=Tom, age=28, email=test3@baomidou.com)]
System.out.println(page.getCurrent());
System.out.println(page.getPages());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
3.6删除操作
3.6.1根据id删除
@Test
public void testDeleteById(){
int result = userMapper.deleteById(8L);
System.out.println(result);
}
3.6.2批量删除
@Test
public void testDeleteBatchIds() {
int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10));
System.out.println(result);
}
3.6.3逻辑删除
- 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除数据
- 逻辑删除:假删除,将对应数据中代表是否被删除字段状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录
3.6.1在表中添加字段,对应实体类添加属性,作为逻辑删除标志
ALTER TABLE `user` ADD COLUMN `deleted` boolean
3.6.2在实体类作为逻辑删除标志的属性上面添加注解
package com.jq.ggkt_mp_demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
//逻辑删除标志
@TableLogic
private Integer deleted;
}
3.6.3在配置文件中,约定规则
mybatisPlus 默认 0没有删 1已删除,如果设置的和MybatisPlus一样则无需配置
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
4.MybatisPlus条件构造器
- Wrapper : 条件构造抽象类,最顶端父类
- AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
- QueryWrapper : Entity 对象封装操作类,不是用lambda语法
- UpdateWrapper : Update 条件封装,用于Entity对象更新操作
- AbstractLambdaWrapper : Lambda 语法使用 Wrapper统一处理解析 lambda 获取 column
- LambdaQueryWrapper :看名称也能明白就是用于Lambda语法使用的查询Wrapper
- LambdaUpdateWrapper : Lambda 更新封装Wrapper
4.1QueryWrapper使用
4.1.1 ge、gt、le、lt
ge
:>=gt
:>le
:<=lt
:<
两个参数: 第一个参数为数据库表字段名称,第二个参数值@Test public void testSelect() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.ge("age", 28); List<User> users = userMapper.selectList(queryWrapper); System.out.println(users); }
4.1.2 eq、ne
-
eq
: = -
ne
: !=
注意:seletOne返回的是一条实体记录,当出现多条时会报错@Test public void testSelectOne() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", "Tom"); User user = userMapper.selectOne(queryWrapper); System.out.println(user); }
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 AND name = ?
4.1.3 like、likeLeft、likeRight
selectMaps返回Map集合列表
@Test
public void testSelectMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.like("name", "e")
.likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回值是Map列表
maps.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version
FROM user WHERE deleted=0 AND name LIKE ? AND email LIKE ?
4.1.4 orderByDesc、orderByAsc
orderByDesc
:降序排序orderByAsc
:升序排序
@Test
public void testSelectListOrderBy() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version
FROM user WHERE deleted=0 ORDER BY id DESC
4.2LambdaQueryWrapper 使用
@Test
public void testLambdaQuery() {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getAge,30);
queryWrapper.like(User::getName,"张");
List<User> list = userMapper.selectList(queryWrapper);
System.out.println(list);
}
SELECT id,name,age,email,create_time,update_time,deleted,version
FROM user WHERE deleted=0 AND age = ? AND name LIKE ?
5.MybatisPlus封装Service层
5.1创建service
public interface UserService extends IService<User> {
}
5.2创建Service实现类
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
5.3方法调用测试
@SpringBootTest
class TestApplicationTests {
//注入service
@Autowired
private UserService userService;
//查询表所有数据
@Test
public void findAll() {
List<User> userList = userService.list();
for (User user:userList) {
System.out.println(user);
}
}
}