2、快速入门
1、导入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2、连接数据库
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SpjJWwbB-1640169265684)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211221235201158.png)]
自动拼接动态sql
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vpg5Mjjl-1640169265686)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222000145949.png)]
7、自动填充
方式一、数据库级别
create_time
update_time
private Date createTime;
private Date updateTime;
工作中不允许
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ddWoH7BA-1640169265687)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222001213459.png)]
方式二、代码级别
1、删除数据库默认值、更新操作
2、字体类字段属性需要增加注解
//字段添加填充内容
@TableField(fill= FieldFill.INSERT)
private Date createTime;
@TableField(fill=FieldFill.INSERT_UPDATE)
private Date updateTime;
3、编写处理器处理
@Slf4j
@Component //不要忘记把处理器加到ioc容器中
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);
}
}
4、测试更新
5、观察时间
8、乐观锁
无论干什么都认为不会出问题,从而不去上锁。
如果出现问题,再次更新至测试
version、new version
悲观锁:无论做什么,都先上锁,在操作。
9、查询操作
1、单个查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
2、批量查询实现
测试代码
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N3NH2ypS-1640169265688)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222004210560.png)]
3、条件查询 map
测试
public void testMapSelect(){
HashMap<String,Object> map=new HashMap<>();
map.put("name","kkf");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-stY91irD-1640169265688)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222010150869.png)]
10、分页查询实现
1、配置拦截器插件
一开始最上面的注解忘记打了,所以分页插件不能生效,
@MapperScan("com.kuang.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
PaginationInterceptor paginationInterceptor=new PaginationInterceptor();
return new PaginationInterceptor();
}
}
//测试分页查询 @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()); }
11、删除操作
1、根据id删除
测试
public void testDeleteById(){ userMapper.deleteById(1L); }
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1Vr42jYK-1640169265690)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222091522687.png)]
2、批量删除
测试代码
public void testBatchDelete(){ int i = userMapper.deleteBatchIds(Arrays.asList(1, 2, 3)); System.out.println(i); }
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CHDJuXtQ-1640169265692)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222094220636.png)]
3、根据map删除
测试代码
public void testByMap(){ HashMap map=new HashMap(); map.put("name","Zhdleed"); userMapper.deleteByMap(map); }
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fHMvc5px-1640169265692)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222094513032.png)]
12、逻辑删除
1、新增一个字段在数据库中
2、实体类增加属性
3、逻辑删除
@TableLogic private Integer deleted;
代码
public void deleteById(){ int i = userMapper.deleteById(1113L); }
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eoTTiB9x-1640169265693)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222095724735.png)]
4、做一个查询
这里可以看到,对于逻辑删除后的数据,是查询不到的
测试代码
public void test2(){ User user = userMapper.selectById(1113L); System.out.println(user); }
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PsVmTTgF-1640169265694)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222100022733.png)]
13、性能分析插件
1、作用
性能分析拦截器,用于输出每条sql语句以及执行时间。
2、导入插件
添加在配置类中
这里一些具体参数没听课的话,不太明确。
//性能分析插件 @Bean @Profile({"dev","test"})//设置devhe test环境开启 public PerformanceInterceptor performanceInterceptor(){ PerformanceInterceptor performanceInterceptor=new PerformanceInterceptor(); performanceInterceptor.setMaxTime(1); performanceInterceptor.setFormat(true); return performanceInterceptor; }
3、添加设置开发环境
#设置开发环境spring.profiles.active=dev
4、测试查询
代码
public void test3(){ List<User> users = userMapper.selectBatchIds(Arrays.asList(1111,1112)); users.forEach(System.out::println); }
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gKtpCj9K-1640169265694)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222101348017.png)]
实际上没有问题,但是只要超出设定时间,会抛出异常
14、条件查询器Wrapper
案例一 多条件查询
可以和wrapper比较
代码
@SpringBootTestpublic class WrapperTest { @Autowired private UserMapper userMapper; @Test void contextLoads(){ //查询name不为空,并且邮箱不为空,年龄大于等于12 QueryWrapper<User> wrapper=new QueryWrapper<User>(); wrapper .isNotNull("name") .isNotNull("email") .ge("age",12); userMapper.selectList(wrapper).forEach(System.out::println); }}
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SofkASBH-1640169265695)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222104820441.png)]
案例2、
代码
void test2(){ //查询名字 QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.eq("name","不是这个名"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j9PN7KJe-1640169265696)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222105613803.png)]
案例三
代码
QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.between("age",20,30); Integer count = userMapper.selectCount(wrapper); System.out.println(count);
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CrUwWaOn-1640169265697)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222105936487.png)]
案例四 模糊查询 左右
代码
QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper .notLike("name","e"); //.likeLeft("email","4"); List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); maps.forEach(System.out::println);
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3UcFfDNc-1640169265697)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222110549726.png)]
案例五 子查询使用
代码
QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.inSql("id","select id from user where id>3"); List<Object> objects = userMapper.selectObjs(wrapper); objects.forEach(System.out::println);
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EeHCF4zh-1640169265698)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222111123221.png)]
案例六 查询结果排序
代码
QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.orderByAsc("id"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println);
截图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uHfyIHeX-1640169265698)(C:\Users\Shenjunhann\AppData\Roaming\Typora\typora-user-images\image-20211222112044699.png)]
15/16 代码自动生成器
后台数据库自动生成
AutoGenerator
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.setFileOverride(false); gc.setOpen(false); gc.setServiceName("%sService");//去service的i前缀 gc.setIdType(IdType.ID_WORKER); gc.setSwagger2(true); //这里少了一些东西 mpg.setGlobalConfig(gc); //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDriverName("dd"); dsc.setUsername("root"); dsc.setUrl("dfds"); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("blog"); pc.setParent("com.kuang"); pc.setEntity("pojo"); mpg.setPackageInfo(pc); //策略 StrategyConfig strategy=new StrategyConfig(); strategy.setInclude("user");//设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); //自动lombok 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<>(); strategy.setTableFillList(tablefills); //乐观锁 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true); mpg.setStrategy(strategy); mpg.execute();//执行 }
改其他表,只需要修改user
很强大
如果需要生成多个表,String
简化开发效率。