范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文
国学影视

MyBatisPlus保姆级快速上手教程

  为简化开发而生
  Mybatis简化JDBC操作
  MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。  1、特性无侵入  :只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑  损耗小  :启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作  强大的 CRUD 操作  :内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求  支持 Lambda 形式调用  :通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错  支持主键自动生成  :支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题  支持 ActiveRecord 模式  :支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作  支持自定义全局通用操作  :支持全局通用方法注入( Write once, use anywhere )  内置代码生成器  :采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用  内置分页插件  :基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询  分页插件支持多种数据库  :支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库  内置性能分析插件  :可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询  内置全局拦截插件  :提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作  2、支持数据库mysql 、 mariadb 、 oracle 、 db2 、 h2 、 hsql 、 sqlite 、 postgresql 、 sqlserver  达梦数据库 、 虚谷数据库 、 人大金仓数据库  3、快速开始1、创建数据库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) ); 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、新建Spring Boot项目导入依赖  <  dependency  > <groupId >org.springframework.bootgroupId > <artifactId >spring-boot-devtoolsartifactId > <scope >runtimescope > <optional >trueoptional > dependency > <dependency > <groupId >mysqlgroupId > <artifactId >mysql-connector-javaartifactId > dependency > <dependency > <groupId >org.projectlombokgroupId > <artifactId >lombokartifactId > <optional >trueoptional > dependency >    <dependency > <groupId >com.baomidougroupId > <artifactId >mybatis-plus-boot-starterartifactId > <version >3.3.1.tmpversion > dependency >连接数据库spring:   datasource:   url:   jdbc:mysql:  //localhost:3306/mybatisplus  ?useSSL=true  &useUnicode=true  &characterEncoding=UTF-8  &serverTimezone=GMT #useSSL安全连接 useUnicode编码 characterEncoding编码格式 serverTimezone时区   username:   用户名 password:   密码 driver-class  -name  : com  .mysql  .cj  .jdbc  .Driver  创建实体类User@Data   @AllArgsConstructor   @NoArgsConstructor   public   class   User   { private   Long id; private   String name; private   Integer age; private   String email; }实现接口UserMapper//@Mapper   @Repository   //代表持久层   public   interface   UserMapper   extends   BaseMapper  <User > { //所有的CRUD已经编写完成   }在 Spring Boot 启动类中添加 @MapperScan   注解,扫描 Mapper 文件夹@SpringBootApplication   @MapperScan  ("com.xiaobear.mapper"  ) //扫描文件夹   public   class   MybatisplusApplication   { public   static   void   main  (String[] args) { SpringApplication.run(MybatisplusApplication.class, args); } }测试@SpringBootTest   class   MybatisplusApplicationTests   { @Autowired   private   UserMapper userMapper; @Test   void   contextLoads  () { //查询所有用户   List list = userMapper.selectList(null  ); list.forEach(System.out::println); } }4、配置日志
  使用默认控制台输出日志  #配置日志 mybatis-plus:   configuration:     log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  5、CRUD扩展Insert//    测试插入     @Test     public void testInsert(){         User user = new User();         user.setName("小熊");         user.setAge(18);         user.setEmail("2861184805@qq.com");         int insert = userMapper.insert(user); //自动生成id         System.out.println(insert);         System.out.println(user);     } }
  结果
  主键生成策略雪花算法:Twitter 利用 zookeeper 实现了一个全局ID生成的服务 Snowflake:github.com/twitter/sno…:
  snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0
  主键自增
  我们配置主键自增  实体类字段上加上@TableId(type = IdType.AUTO)  数据库字段上一定要自增
  再次测试即可  public enum IdType { AUTO(0), //数据库id自增 NONE(1), //未设置主键 INPUT(2), //手动输入 ASSIGN_ID(3), //默认全局id ASSIGN_UUID(4), //全局唯一id  @Deprecated   ID_WORKER(3  ), @Deprecated   ID_WORKER_STR(3  ), //ID_WORKER字符串表示法   @Deprecated   UUID(4  ); private   final   int   key; private   IdType  (int   key) { this  .key = key;} public   int   getKey  () { return   this  .key;}}update @Test     public void testupdate(){         //通过条件自动拼接动态sql         User user = new User();         user.setId(6L);         user.setName("你是最棒的");         int i = userMapper.updateById(user);  //updateById参数是一个对象         System.out.println(i);     } }
  自动填充
  数据库级别(工作中不使用)
  1、在表中字段增加create_time、update_time
  2、通过测试插入方法  private Date createTime; private Date updateTime;
  3、查看结果
  代码级别
  1、实体类属性上增加注解  @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime;
  2、实现元对象处理器接口:  com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
  自定义实现类 MyMetaObjectHandler  @Component  //加入到IOC容器里 @Slf4j 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);     } }
  3、测试插入,观察时间  乐观锁
  十分乐观,它总是认为不会出现问题,无论干什么都不上锁,如果出现了问题,再次更新值测试!
  乐观锁实现方式:  取出记录时,获取当前version  更新时,带上这个version  执行更新时, set version = newVersion where version = oldVersion  如果version不对,就更新失败
  1、给数据库新增字段verison,默认值为1
  2、实体类新增字段  @Version //乐观锁注解 private Integer version;
  3、注册插件  @Configuration @MapperScan("com.xiaobear.mapper") public class MybatisPlusConfig {     //注册乐观锁插件     @Bean     public OptimisticLockerInterceptor optimisticLockerInterceptor() {         return new OptimisticLockerInterceptor();     } }
  4、测试  @Test public void testOptimisticLocker(){     //查询用户信息     User user = userMapper.selectById(1L);     //修改信息     user.setName("xiaobear");     user.setAge(2);     //执行     int update = userMapper.updateById(user);     System.out.println(update);  } //测试失败 @Test public void testOptimisticLocker2(){     User user = userMapper.selectById(1L);     user.setName("xiaobear");     user.setAge(2);     User user2 = userMapper.selectById(1L);     user2.setName("xiaobear111");     user2.setAge(10);     //模拟另一个线程进行插队操作     int update = userMapper.updateById(user);     int update2 = userMapper.updateById(user2);     System.out.println(update);     System.out.println(update2); }  悲观锁
  十分悲观,它总是认为会出现问题,无论干什么都会上锁,再去操作!  查询操作 //单个查询     @Test     public void testSelect(){         User user = userMapper.selectById(2L);         System.out.println(user);      }      //批量查询     @Test     public void testSelectByBatchId(){         List users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));         users.forEach(System.out::println);     }      //条件查询map     @Test     public void testSelectByBatchIds(){         HashMap map = new HashMap<>();         map.put("name","xiaobear");         List users = userMapper.selectByMap(map);         users.forEach(System.out::println);      }  分页查询
  分页插件    //分页插件     @Bean     public PaginationInterceptor paginationInterceptor() {           return new PaginationInterceptor();        /* PaginationInterceptor paginationInterceptor = new PaginationInterceptor();         // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false         // paginationInterceptor.setOverflow(false);         // 设置最大单页限制数量,默认 500 条,-1 不受限制         // paginationInterceptor.setLimit(500);         // 开启 count 的 join 优化,只针对部分 left join         paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));         return paginationInterceptor;*/     }
  测试  //测试分页插件 @Test public void testPage(){     //参数一:当前页 参数二:页面大小     Page page = new Page<>(1,5);     userMapper.selectPage(page,null);     page.getRecords().forEach(System.out::println);     System.out.println(page.getTotal()); }  删除操作//测试删除 @Test public void deleteById(){     int i = userMapper.deleteById(1L);     System.out.println(i); } //测试id批量删除 @Test public void deleteById2(){     userMapper.deleteBatchIds(Arrays.asList(1L,2L,3L)); }  //通过map删除 @Test public void testDeleteMap(){     HashMap map = new HashMap<>();     map.put("name","小熊");     userMapper.deleteByMap(map); }  逻辑删除物理删除:从数据库中直接删除
  逻辑删除:在数据库没有移除,而是通过一个变量来让他失效!防止数据丢失,类似回收站
  数据库添加字段,实体类上加上字段  @TableLogic private Integer deleted;
  测试删除、查询  6、性能分析插件
  性能分析拦截器,用于输出每条 SQL 语句及其执行时间  /**    * SQL执行效率插件    */   @Bean   @Profile({"dev","test"})// 设置 dev test 环境开启   public PerformanceInterceptor performanceInterceptor() {       return new PerformanceInterceptor();   }  7、条件构造器wrapper    @Autowired     private UserMapper userMapper;     @Test     void contextLoads() {         QueryWrapper wrapper = new QueryWrapper<> ();         wrapper                 .isNotNull("name")                 .isNotNull("email")                 .ge("age",3);         userMapper.selectList(wrapper).forEach(System.out::println);     }     @Test     void test(){         QueryWrapper wrapper = new QueryWrapper<>();         wrapper.eq("name","Tom"); //查询名字         User user = userMapper.selectOne(wrapper); //查询一个数据         System.out.println(user);     }     @Test     void test2(){         //查询年龄10-20         QueryWrapper wrapper = new QueryWrapper<>();         wrapper.between("age",10,20);         Integer count = userMapper.selectCount(wrapper);         System.out.println(count);     }     @Test     void test3(){         //模糊查询         QueryWrapper wrapper = new QueryWrapper<>();         wrapper                 .notLike("name","e")                 .likeRight("email","t");         List> maps = userMapper.selectMaps(wrapper);         maps.forEach(System.out::println);     }      @Test     void test4(){         //         QueryWrapper wrapper = new QueryWrapper<>();         wrapper.inSql("id","select id form user where id<3");         List objects = userMapper.selectObjs(wrapper);         objects.forEach(System.out::println);     }  8、代码生成器public class XiaoBearCode {      public static void main(String[] args) {         AutoGenerator mpg = new AutoGenerator();         // 全局配置         GlobalConfig gc = new GlobalConfig();         String projectPath = System.getProperty("user.dir");         gc.setOutputDir(projectPath + "/src/main/java");         gc.setAuthor("xiaobear");         gc.setOpen(false);         // gc.setSwagger2(true); 实体属性 Swagger2 注解         mpg.setGlobalConfig(gc);          // 数据源配置         DataSourceConfig dsc = new DataSourceConfig();         dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT");         // dsc.setSchemaName("public");         dsc.setDriverName("com.mysql.cj.jdbc.Driver");         dsc.setUsername("用户名");         dsc.setPassword("密码");         mpg.setDataSource(dsc);          // 包配置         PackageConfig pc = new PackageConfig();         pc.setModuleName("blog");         pc.setParent("com.xiaobear");         pc.setEntity("pojo");         pc.setMapper("mapper");         pc.setService("com/xiaobear/service");         pc.setServiceImpl("com.xiaobear/Service/Impl");         pc.setController("com/xiaobear/controller");         mpg.setPackageInfo(pc);          // 策略配置         StrategyConfig strategy = new StrategyConfig();         strategy.setNaming(NamingStrategy.underline_to_camel);         strategy.setColumnNaming(NamingStrategy.underline_to_camel);         strategy.setEntityLombokModel(true);  //自动lombok         strategy.setRestControllerStyle(true);         // 公共父类         strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");         // 写于父类中的公共字段         strategy.setSuperEntityColumns("id");         strategy.setInclude("user");//映射的表         strategy.setLogicDeleteFieldName("deleted");  //逻辑删除字段         //自动填充策略         TableFill gmt_create = new TableFill("gmt_create", FieldFill.INSERT);         TableFill gmt_modified = new TableFill("gmt_strate", FieldFill.INSERT);         ArrayList list = new ArrayList<>();         list.add(gmt_create);         list.add(gmt_modified);         strategy.setTableFillList(list);         //乐观锁         strategy.setVersionFieldName("version");         strategy.setRestControllerStyle(true);  //驼峰         strategy.setControllerMappingHyphenStyle(true);  //localhost:8080/hello_id_1         strategy.setTablePrefix(pc.getModuleName() + "_");         mpg.setStrategy(strategy);         mpg.setTemplateEngine(new FreemarkerTemplateEngine());          mpg.execute(); //执行     }  }
  错误:  19:39:38.943 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...========================== Exception in thread "main" java.lang.NoClassDefFoundError: freemarker/template/Configuration     at com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine.init(FreemarkerTemplateEngine.java:41)     at com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine.init(FreemarkerTemplateEngine.java:34)     at com.baomidou.mybatisplus.generator.AutoGenerator.execute(AutoGenerator.java:103)     at com.xiaobear.XiaoBearCode.main(XiaoBearCode.java:66) Caused by: java.lang.ClassNotFoundException: freemarker.template.Configuration     at java.net.URLClassLoader.findClass(URLClassLoader.java:382)     at java.lang.ClassLoader.loadClass(ClassLoader.java:418)     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)     at java.lang.ClassLoader.loadClass(ClassLoader.java:351)     ... 4 more
  解决:  导入模板引擎依赖
  org.freemarker freemarker 2.3.30
长路游戏世界因发现精彩,快乐因自己寻找长路上的时间如何来打发?孩子向一位难得的好老师学习美术,很多次是骑车过去,单程10公里多,需要在城郊和乡间骑很长时间。每次出发时的任务是设计长路游戏,让长路变丰富,感觉时间变快。大走进照母山发现新领域新赛道大型调研报道成立四年用户超6000万这家渝企有何高招来源重庆日报网企业名片空间视创(重庆)科技股份有限公司空间视创(重庆)科技股份有限公司2018年8月成立于重庆两江新区,是国家高新技术企业重庆市专精特新企业重庆市重点软件和信息服务游本昌版本的济公如何突破原著的限制取得成功说到济公,相信大家对游本昌老师扮演的济公印象最深。鞋儿破帽儿破身上的袈裟破这一首济公的主题曲常在脑中回响。剧中那为人正直,行事疯癫的济公深受观众们喜爱。游本昌版济公改编自清朝小说济VR游戏GorillaTag营收超2600万美元,月活用户超230万(映维网Nweon2023年01月20日)自2021首次在AppLab亮相以来,VR猩猩模拟器GorillaTag的人气稳步增长,并日益成为这个平台最受欢迎的内容之一。同样,这款作WhatsApp增加了代理支持,让用户在互联网被封锁时也能保持在线布莱恩林恩2023年1月11日这张图片显示的是WhatsApp的标志即时通讯服务软件WhatsApp增加了一种辅助工具,该辅助工具帮助其用户在互联网遭到封锁时也能保持在线。这家由F索尼公开2022年度PlayStationVR游戏下载榜1月17日,索尼公开了2022年度PlayStation商店的游戏下载榜,其中PSVR游戏的下载量TOP10如下图(注左右两栏分别为北美加拿大和欧洲地区)。意料之中的是,BeatS进户门要不要加装指纹密码锁?终于有师傅说出实话,多亏好心提醒大家好,我是小雷,今天再次来跟大家聊聊进户门要不要安装指纹密码锁,如果要是安装指纹密码锁的话,我们应该怎么样去选择,在我前面发布的文章中就有很多的网友,关于指纹密码锁的一些问题都存日本持续衰落,GDP在全球占比跌破5,沦为普通中等强国众所周知,二战后世界形成了两极格局,苏联解体后世界又形成了一超多强格局。美国一个超级强国,加上众多中等强国,这些中等强国包括中国日本俄罗斯德国英国法国意大利印度等。虽然都叫中等强国大地主刘文彩病死之后,他的五个妻妾都去了哪里,结局又如何?在阅读此文前,诚邀您点击一下关注,既方便您进行讨论与分享,又给您带来不一样的参与感,感谢您的支持。引言封建社会的大地主,富绅是怎样生活的你想知道吗?如果想的话,那一定要去成都大邑县1967年,87岁的孔祥熙重病后,不甘地念叨孔家的香火,要断了吗前言1965年,已经85岁高龄的孔祥熙接到小儿子孔令杰的电报,他的长孙出生了。孔祥熙激动不已,哈哈大笑几声欣慰地说孔家终于有后了。1967年7月,美国纽约的一家医院接收了病重的孔祥高丽时刻关注北元与明朝两方势力变化,以选择更好的政治站位北元册封辛禑过程高丽时刻关注北元与明朝两方势力变化,以选择更好的政治站位洪武六年(1377年)七月,北元遣徹里帖木儿至高丽,与辛禑商议夹击明朝定辽卫。但是对于高丽来说,明朝日益兴盛
苏州首个油氢电综合加能站投入使用,上汽借氢风加速发展2020年,中国确立了碳达峰碳中和的战略目标,双碳目标对于产业结构调整能源体系建设低碳交通运输体系与绿色城乡建设等方面做出部署。作为碳排放大户的汽车产业也在谋求多样化发展,在混动纯法治日报刊发邹平市阳光透明酬金制典型经验11月23日,法治日报对邹平市小区物业阳光透明酬金制管理模式进行宣传报道,全文如下阳光透明酬金制解开物业纠纷硬疙瘩记者探访城市小区治理邹平样板本报记者姜东良梁平妮物业服务不到位公共修特斯拉成新业务,通用汽车电动车业务将提前五年盈利据纽约时报报道,通用汽车近日宣布,预计到2025年在北美市场销售的电动汽车将实现稳定盈利,达到传统燃油车同等水平。这比通用汽车在去年承诺的2030年实现盈利提前了5年时间。内燃机时机构预计2023年新能源汽车销量增长31!逾30亿元大单资金涌入这些股票本报记者任世碧近期支持新能源汽车消费的利好政策不断,为板块企稳反弹提供助力。11月21日,工业和信息化部国家发展改革委国务院国资委联合印发关于巩固回升向好趋势加力振作工业经济的通知最新龙虎榜动向2。22亿资金抢筹九安医疗,机构和北向资金共同卖出以岭药业(名单)11月24日,上证指数下跌0。25,深证成指下跌0。15,创业板指下跌0。21。盘后龙虎榜数据显示,共有40只个股因当日异动登上龙虎榜,资金净流入最多的是九安医疗(002432。S前10月软件业务收入同比增10数据来源工信部制图蔡华伟本报北京11月24日电(记者王政)记者24日从工信部获悉前10月,我国软件和信息技术服务业运行态势平稳向好,软件业务收入84214亿元,同比增长10,增速较龙虎榜医药股再现上亿资金交易,九安医疗龙虎榜净买入2。21亿元,东方路大买2。82亿元以岭药业一龙虎榜净买入额排名11月24日龙虎榜出炉,一共有48家公司上榜。资金净流入最多的是九安医疗,周四涨停,龙虎榜净买入2。21亿元,换手率17。89。龙虎榜数据显示,1家机构净买入7藏不住了!西藏这座低调小城,一入冬就成了中国的北欧一入冬波密就成了真正的冰雪王国有人说全世界没有哪个地方像波密这样如此四季分明,又如此冰清玉洁所以不管是哪个季节来过这里你总想把它的四季都感受一次特别是冬天傲立千年的冰川尤为壮观每一上交所副总经理刘逖上交所四大举措布局ETF市场发展刘逖。资料图11月15日,在2022中国资产管理年会上,上海证券交易所副总经理刘逖在会上以创新ETF市场发展,拥抱时代新机遇为主题发表了演讲。今年以来,沪市ETF成交额已突破12。MTK天玑8200芯片规格曝光我国软件业务收入84214亿元芯闻速递两分钟了解芯片大事联发科天玑8200芯片规格曝光据爆料称,小米Redmi60系列手机和iQOONeo7SE将搭载该芯片。现在微博博主数码闲聊站曝光了天玑8200的关键规格,表明它们少儿美术一幅世界杯进球就画好啦1课程准备认识世界杯,你知道今年的世界杯是在哪里举行吗?世界杯的吉祥物叫什么名字呢?你有喜欢的球星吗?一起画画你看到的世界杯吧2工具准备白纸铅笔马克笔橡皮擦,黑色水笔。折纸,剪刀,