官网地址:https://baomidou.com/pages/226c21/#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B
步骤
DROP TABLE IF EXISTS user;
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)
);
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
-- 真实开发中,还会有version(乐观锁)、delete(逻辑删除)、gmt_create 、gmt_modified
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.0.5version>
dependency>
说明:尽量不要同时导入mybatis和mybatis-plus!有版本差异
spring.datasource.username=root
spring.datasource.password=123456
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
# mysql8 驱动不同,需要加时区配置
package com.qian.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private int age;
private String email;
}
package com.qian.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qian.pojo.User;
import org.springframework.stereotype.Repository;
@Repository //代表持久层
//在对应的Mapper上面继承基本的类 BaseMapper
public interface UserMapper extends BaseMapper<User> {
//所有的CRUD操作已经编写完成,不需要编写mapper.xml
}
**在对应的Mapper上面继承基本的类 BaseMapper **
package com.qian;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//扫描我们的mapper文件夹
@MapperScan("com.qian.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
package com.qian;
import com.qian.mapper.UserMapper;
import com.qian.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
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//查询全部用户 参数是一个Wrapper ,条件构造器,这里我们先不用null
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
==> Preparing: SELECT id,name,age,email FROM user
==> Parameters:
<== Columns: id, name, age, email
<== Row: 1, Jone, 18, test1@baomidou.com
<== Row: 2, Jack, 20, test2@baomidou.com
<== Row: 3, Tom, 28, test3@baomidou.com
<== Row: 4, Sandy, 21, test4@baomidou.com
<== Row: 5, Billie, 24, test5@baomidou.com
<== Total: 5
//测试插入
@Test
public void testInsert(){
User user=new User();
user.setName("狂神说java");
user.setAge(3);
user.setEmail("[email protected]");
int insert = userMapper.insert(user);
System.out.println(insert);//1
System.out.println(user);//User(id=1556204931867017217, name=狂神说java, age=3, [email protected])
//id会自动填充
}
数据库插入的id的默认值为:全局的唯一id,
分布式唯一id生成的方法:
我们所用的mybatis-plus 实现id生成的方式就是雪花算法
雪花算法 :核心思想是:采用bigint(64bit)作为id生成类型,并将所占的64bit 划分成多段。(Twitter的snowflake算法)
@TableId(type = IdType.ID_WORKER)
主键自增,我们需要配置主键自增:
@TableId(type = IdType.INPUT) 设置为手动输入id ,需要手动插入id ,否则就会输出null
//测试更新
@Test
public void testUpdate(){
User user=new User();
//通过条件自动拼接动态sql
user.setId(1L);
user.setName("关注公众号");
//注意:updateById()参数是一个 对象!
int i = userMapper.updateById(user);
System.out.println(i);
}
所有的sql都是自动帮你动态配置的!
创建时间、修改时间!这些操作都应该自动化完成的,我们不希望手动更新!
成功更新时间!
(不推荐使用,工作中不允许你修改数据库)
删除数据库中这两个字段的默认值、更新操作
实体类的字段属性上增加注解
// public enum FieldFill {
// DEFAULT,
// INSERT,
// UPDATE,
// INSERT_UPDATE;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
package com.qian.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");
//setFieldValByName():String fieldName, Object fieldVal, MetaObject metaObject
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);
}
}
官网解释:
OptimisticLockerInnerInterceptor
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
- 取出记录时,获取当前 version
- 更新时,带上这个 version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果 version 不对,就更新失败
乐观锁:1、先查询。获得当前版本号 version=1
--- A线程
update user set name = "kuangshen",version=version+1
where id = 2 and version=1 --- 更新时要带上这个version
--- 执行更新时,使获得的当前版本的version=new version(一般就是自动加1)
--- 如果此时线程B抢先完成更新,那么version=2,就不是A线程获得到的version号,所以就A就会更新失败
@Version //乐观锁注解
private int version;
package com.qian.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@MapperScan("com.qian.mapper")
@EnableTransactionManagement //开启事务管理
@Configuration //配置类
public class MybatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
//测试乐观锁成功
@Test
public void testOptimisticLocker(){
//查询用户信息
User user = userMapper.selectById(1L);
//修改用户信息
user.setName("xqh");
user.setEmail("[email protected]");
//执行更新操作
userMapper.updateById(user);
}
//==> Preparing: UPDATE user SET name=?, age=?, email=?, version=?, create_time=?, update_time=? WHERE id=? AND version=? 会把version带上
//测试乐观锁失败 多线程下
@Test
public void testOptimisticLocker2(){
//线程1
User user = userMapper.selectById(2L);
user.setName("xqh11");
user.setEmail("[email protected]");
//模拟另外一个线程执行插队操作
User user2 = userMapper.selectById(2L);
user2.setName("xqh22");
user2.setEmail("[email protected]");
userMapper.updateById(user2); //线程1先查询,然后被线程2插队更新。
userMapper.updateById(user);//有乐观锁,所以更新user1更新失败。数据库中name修改的还是xqh22.“一旦被插队,就更新失败”
}
//测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
//测试查询多个用户
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
//条件查询 map
@Test
public void testSelectByMap(){
HashMap<String,Object> map = new HashMap<>();
//自定义要查询
map.put("name","xqh");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
//查询数据库中所有信息
@Test
public void testSelectList(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
1)配置拦截器组件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
2)测试分页查询
//测试分页查询
@Test
public void testPage(){
Page<User> page = new Page<>(1, 5);//当前页,页面大小。第一页显示五条
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());//打印出总共多少行数据
}
//测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(1556204931867017217L);
}
//批量删除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(3,4,5));
}
//条件删除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","狂神说java");
userMapper.deleteByMap(map);
}
例如:管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!
1)在数据库表中增加deleted字段,长度1,默认值为0
2)实体类中添加属性
@TableLogic //逻辑删除
private int deleted;
3)注册逻辑删除组件
//逻辑删除组件
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
//注意,高版本的话不需要注册这一步,具体情况参照官网
4)配置逻辑删除
# 配置逻辑删除 已删除1 未删除0
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
5)测试
//测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(4L);
}
虽然是删除操作但是sql语句执行的是更新 :UPDATE user SET deleted=1 WHERE id=? AND deleted=0
并且数据也并没有消失,仍然储存在数据库中,只是deleted=1
//再对这个删除的数据进行查询
public void testSelectById(){
User user = userMapper.selectById(4L);
System.out.println(user);
}
**sql查询语句会自动带上 AND deleted=0 ** ==> Preparing: SELECT id,name,age,email,version,deleted,create_time,update_time FROM user WHERE id=? AND deleted=0
所以查出来为null!!查询时会自动过滤掉deleted=1即被逻辑删除的数据!!
MP也提供了性能分析插件! 如果超过这个时间就停止运行
//sql执行效率插件
@Bean
@Profile({"dev","test"}) //设置 dev test 环境开启,保证我们的效率
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); //ms,设置sql执行的最大时间,如果超过了则不执行
performanceInterceptor.setFormat(true);//sql语句格式化
return performanceInterceptor;
}
performanceInterceptor.setMaxTime(100); :设置sql执行运行的最大时间,如果sql执行时间超过,就会执行失败
performanceInterceptor.setFormat(true); :将sql语句格式化
# 激活为开发环境
spring.profiles.active=dev
// The SQL execution time is too large, please optimize ! 超过规定时间就会抛出异常
使用性能分析插件,可以帮助我们提高效率!找出效率低的sql执行!
十分重要,我们写一些复杂的sql就可以使用它来替代!
@Test
void contextLoads() {
//查询name不为空的用户,并且邮箱不为空,并且年龄大于等于12的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",12); //大于等于12
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
//查询名字等于xqh的用户
@Test
void test2(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","xqh"); //eq:相等
User user = userMapper.selectOne(wrapper);
System.out.println(user);
}
//查询between。。and 查询年龄在20~30岁之间的用户
@Test
void test3(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30);//between:多少到多少之间
Integer integer = userMapper.selectCount(wrapper);//查询结果数
System.out.println(integer); //2
}
//模糊查询
@Test
void test4(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.notLike("name","e") //不包含e
//左查询%t 右查询t%
.likeRight("name","x");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//id在子查询中查出来
wrapper.inSql("id","select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//通过age进行降序排序
wrapper.orderByDesc("age");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
dao、pojo、service、controller自己编写完成!
官网学习:https://baomidou.com/pages/d357af/#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B
package com.qian;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.sql.Array;
import java.util.ArrayList;
//代码自动生成器
public class Code {
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("xqh");
gc.setOpen(false);//是否打开windows文件夹
gc.setFileOverride(false);//是否覆盖
gc.setServiceName("%sService");//去掉Service的i前缀
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//2、设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.qian");
pc.setEntity("pojo");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user");//设置要映射的表
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setLogicDeleteFieldName("deleted");
//自动填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
//乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
//执行
mpg.execute();//执行
}
}