1.前言:
狂神的视频链接:遇见狂神说的个人空间_哔哩哔哩_bilibili
mybaits-plus是一款为简化开发而生的开发框架
官网地址:快速开始 | MyBatis-Plus (baomidou.com)
2.快速开始
1.创建mybaits-plus数据库,进入数据库建表
#创建数据库
create database mybatis-plus;
#使用数据库
use mybatis-plus;
#创建表
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.创建并初始化springboot工程
3.导入依赖
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
4.进入application.propertis进行配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5.创建实体类(pojo),mapper接口
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
//使用了lombok
//在对应的Mapper上面继承基本的类 BaseMapper
@Repository// 代表持久层
public interface UserMapper extends BaseMapper<User> {
// 所有的CRUD操作都已经编写完成了
// 你不需要像以前的配置一大堆文件了!
}
6.在主启动类上添加@MapperScan("com.lx.mapper")去扫描mapper包下的所有接口
@SpringBootApplication
@MapperScan("com.lx.mybatisplus.Mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
7.进入测试类进行测试
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper usermapper;
private Integer id=1;
@Test
void contextLoads() {
List<User> users=mapper.selectList(null);
users.forEach(System.out::println);
}
3.配置日志
进入application.propertis配置日志方便我们观察sql如何运行
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4.CRUD扩展(增改查删)
插入操作(增)
@Test
public void TestInsert(){
User user=new User();
user.setAge(13);
user.setEmail("2335126230@qq.com");
user.setName("李云");
int insert = mapper.insert(user);//自动生成id
System.out.println(insert);//受影响的行数
System.out.println(user);
}
更新操作(改)
@Test
public void TestUpdate(){
User user=new User();
user.setId(6l);
user.setName("狂徒张三");
int i = mapper.updateById(user);
System.out.println(i);
}
条件查询操作(查)
// 查询操作
@Test
public void TestSelectById(){
User user = mapper.selectById(1);
System.out.println(user);
}
// 测试批量查询
public void testSelectByBatchId(){
List<Integer> idList = Arrays.asList(1, 2, 3);
List<User> users = mapper.selectBatchIds(idList);
users.forEach(System.out::println);
}
// 条件查询
@Test
public void testSelectByBatchIds(){
HashMap<String,Object> map=new HashMap<>();
map.put("name","狂徒张三");
map.put("age",13);
List<User> users = mapper.selectByMap(map);
users.forEach(System.out::println);
}
// 测试分页查询
@Test
public void testPage(){
Page<User> page=new Page<>(1,10);
mapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
删除操作(删)
// 根据id删除记录
@Test
public void testDeleteById(){
usermapper.deleteById(1);
}
// 通过id批量删除
@Test
public void testDeleteBatchId(){
mapper.deleteBatchIds(Arrays.asList(8,7,6));
}
// 通过map删除
@Test
public void testDeleteMap(){
HashMap<String,Object>map=new HashMap<>();
map.put("name","Jack");
mapper.deleteByMap(map);
}
5.插件使用
插件使用的方法:
1.在pojo类中增添注解;
2.创建config类,在config类中添加配置(部分插件不需要),
3,进行测试
1.主键自增插件
增添注解
@TableId(type = IdType.AUTO)
private Long id;
进行测试(在增的操作中进行测试)
2.乐观锁
乐观锁的实现方式:
1.取出记录时,获取当前 version
2.更新时,带上这个version
3.执行更新时, set version = newVersion where version = oldVersion
1、给数据库中增加version字段
2、我们实体类加对应的字段,并添加version注解
@Version
private Integer version;
3.到config类中去注册组件
#注册乐观锁插件 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(){ return new OptimisticLockerInterceptor(); }
4.使用修改操作进行测试
3.分页查询插件
1.到config类中注册插件
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
2.直接使用Page对象
// 测试分页查询
@Test
public void testPage(){
Page<User> page=new Page<>(1,10);
mapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
4.性能插件
1.在config类中导入插件
// 性能分析插件
@Bean
@Profile({"dev","test"})
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor=new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100);
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
2.测试
@Test
public void TestSelectById(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
自动填充
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3.到handler类中对注解添加配置
package com.lx.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill....");
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
6.条件改造器:wrapper
写一些复杂的sql用它来代替
@Test
void contextLoa(){
// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于13
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",13);
mapper.selectList(wrapper).forEach(System.out::println);
}
@Test
void test2(){
// 查询名字李云
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.eq("name","李云");
User user = mapper.selectOne(wrapper);
System.out.println(user);
}
@Test
void test3(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.between("age",20,30);
Integer user = mapper.selectCount(wrapper);
System.out.println(user);
}
@Test
void test4(){
// 模糊查询
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper
.notLike("name","e")
.likeRight("email","qq");
List<Map<String, Object>> user = mapper.selectMaps(wrapper);
// Integer user = mapper.selectCount(wrapper);
System.out.println(user);
}
@Test
void test5(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
// id在子查询中查出来
wrapper.inSql("id","select id from user where id<3");
// Integer user = mapper.selectCount(wrapper);
List<Object> objects = mapper.selectObjs(wrapper);
System.out.println(objects);
}
@Test
void test6(){
// 通过id进行排序
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.orderByAsc("id");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
7.代码自动生成器
public class CodeGenerator {
public static void main(String[] args) {
//构建一个代码自动生成器对象
AutoGenerator mpg = new AutoGenerator();
//配置策略
//1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("胡");
gc.setOpen(false);
gc.setFileOverride(false);
gc.setServiceName("%sService");
gc.setIdType(IdType.ID_WORKER);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/illness?
serverTimezone=UTC&useUnicode=true&characterEncoding=utf8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver") ;
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("virus");
pc.setParent("com.hushen");
pc.setEntity("pojo");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("illness");//设置映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
mpg.setStrategy(strategy);
//自动填充
mpg.execute();
}
}