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

阿里一手爆出Springboot整合MybatisPlus(超详细)完整教程

  新建springboot项目
  开发工具:idea2019.2,maven3
  pom.xml                 org.springframework.boot             spring-boot-starter                               org.springframework.boot             spring-boot-starter-web                               mysql             mysql-connector-java             runtime                               org.projectlombok             lombok             true                                        com.baomidou             mybatis-plus-boot-starter             3.2.0                               com.baomidou             mybatis-plus-generator             3.2.0                               org.freemarker             freemarker             2.3.28                               com.alibaba             fastjson             1.2.47           application.yml:server:   port: 8081   servlet:     context-path: /  spring:   datasource:     driver-class-name: com.mysql.cj.jdbc.Driver     url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true     username: root     password: lyja   jackson:     date-format: yyyy-MM-dd HH:mm:ss     time-zone: GMT+8     serialization:       write-dates-as-timestamps: false  mybatis-plus:   configuration:     map-underscore-to-camel-case: true     auto-mapping-behavior: full     log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   mapper-locations: classpath*:mapper/**/*Mapper.xml   global-config:     # 逻辑删除配置     db-config:       # 删除前       logic-not-delete-value: 1       # 删除后       logic-delete-value: 0 mybatisplus分页插件MybatisPlusConfig:package com.example.conf;  import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;  /**  * 配置分页插件  *  */ @Configuration public class MybatisPlusConfig {      /**      * 分页插件      */     @Bean     public PaginationInterceptor paginationInterceptor() {         return new PaginationInterceptor();     } }  mybatisplus自动生成代码GeneratorCodeConfig.java:package com.example.conf;  import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;  import java.util.Scanner;  /**  * 自动生成mybatisplus的相关代码  */ public class GeneratorCodeConfig {      public static String scanner(String tip) {         Scanner scanner = new Scanner(System.in);         StringBuilder help = new StringBuilder();         help.append("请输入" + tip + ":");         System.out.println(help.toString());         if (scanner.hasNext()) {             String ipt = scanner.next();             if (StringUtils.isNotEmpty(ipt)) {                 return ipt;             }         }         throw new MybatisPlusException("请输入正确的" + tip + "!");     }      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("astupidcoder");         gc.setOpen(false);         //实体属性 Swagger2 注解         gc.setSwagger2(false);         mpg.setGlobalConfig(gc);          // 数据源配置         DataSourceConfig dsc = new DataSourceConfig();         dsc.setUrl("jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");         dsc.setDriverName("com.mysql.cj.jdbc.Driver");         dsc.setUsername("root");         dsc.setPassword("lyja");         mpg.setDataSource(dsc);          // 包配置         PackageConfig pc = new PackageConfig(); //        pc.setModuleName(scanner("模块名"));         pc.setParent("com.example");         pc.setEntity("model.auto");         pc.setMapper("mapper.auto");         pc.setService("service");         pc.setServiceImpl("service.impl");         mpg.setPackageInfo(pc);          // 自定义配置 //        InjectionConfig cfg = new InjectionConfig() { //            @Override //            public void initMap() { //                // to do nothing //            } //        };          // 如果模板引擎是 freemarker //        String templatePath = "/templates/mapper.xml.ftl";         // 如果模板引擎是 velocity         // String templatePath = "/templates/mapper.xml.vm";          // 自定义输出配置 //        List focList = new ArrayList<>();         // 自定义配置会被优先输出 //        focList.add(new FileOutConfig(templatePath) { //            @Override //            public String outputFile(TableInfo tableInfo) { //                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! //                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() //                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; //            } //        });         /*         cfg.setFileCreate(new IFileCreate() {             @Override             public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {                 // 判断自定义文件夹是否需要创建                 checkDir("调用默认方法创建的目录");                 return false;             }         });         */ //        cfg.setFileOutConfigList(focList); //        mpg.setCfg(cfg);          // 配置模板         TemplateConfig templateConfig = new TemplateConfig();          // 配置自定义输出模板         //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别         // templateConfig.setEntity("templates/entity2.java");         // templateConfig.setService();         // templateConfig.setController();          templateConfig.setXml(null);         mpg.setTemplate(templateConfig);          // 策略配置         StrategyConfig strategy = new StrategyConfig();         strategy.setNaming(NamingStrategy.underline_to_camel);         strategy.setColumnNaming(NamingStrategy.underline_to_camel);         strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");         strategy.setEntityLombokModel(true);         strategy.setRestControllerStyle(true);          strategy.setEntityLombokModel(true);         // 公共父类 //        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");         // 写于父类中的公共字段 //        strategy.setSuperEntityColumns("id");         strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));         strategy.setControllerMappingHyphenStyle(true);         strategy.setTablePrefix(pc.getModuleName() + "_");         mpg.setStrategy(strategy);         mpg.setTemplateEngine(new FreemarkerTemplateEngine());         mpg.execute();     } }  测试
  建表:
  执行GeneratorCodeConfig.java文件,输入表名user:
  解决方法:在数据库连接中配置添加allowPublicKeyRetrieval=true
  查看生成的文件;
  添加扫描mapper注解
  启动springboot的application启动类:会报错,提示找不到mapper文件,我们需要在springboot启动类上添加扫描mapper的注解: package com.example;  import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication @MapperScan("com.example.mapper") public class DemoApplication {      public static void main(String[] args) {         SpringApplication.run(DemoApplication.class, args);     }  }
  UserController.java中新增接口:   @Autowired     private IUserService userService;     @PostMapping("/getUser")     public User getUser(){         return userService.getById(1);     }
  postman测试:
  没问题。
  上面是mybatisplus测试成功,下面我们继续测试我们自己写的sql是否成功。
  在resources目录下新建mapper文件夹,新建UserMapper.xml文件: <?xml version="1.0" encoding="UTF-8"?>                
  UserMapper.java package com.example.mapper.auto;  import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.model.auto.User;  import java.util.List;  /**  * 

* Mapper 接口 * * * @author astupidcoder * @since 2020-05-13 */ public interface UserMapper extends BaseMapper { public ListfindAllUser(); }   IUserService: package com.example.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.model.auto.User; import java.util.List; /** *

* 服务类 * * * @author astupidcoder * @since 2020-05-13 */ public interface IUserService extends IService { public List findAllUser(); }   UseServiceImpl.java: package com.example.service.impl; import com.example.model.auto.User; import com.example.mapper.auto.UserMapper; import com.example.service.IUserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** *

* 服务实现类 * * * @author astupidcoder * @since 2020-05-13 */ @Service public class UserServiceImpl extends ServiceImpl implements IUserService { @Autowired private UserMapper userMapper; @Override public List findAllUser() { return userMapper.findAllUser(); } }   UserController.java: package com.example.controller; import com.example.model.auto.User; import com.example.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** *

* 前端控制器 * * * @author astupidcoder * @since 2020-05-13 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @PostMapping("/getUser") public User getUser(){ return userService.getById(1); } @PostMapping("/findAllUser") public List findAllUser(){ return userService.findAllUser(); } }   测试findAllUser接口:   常用的工具类:   ResultInfo.java package com.example.conf; import lombok.Data; import java.io.Serializable; /** *返回结果类统一封装 */ @Data public class ResultInfo implements Serializable { // 状态码 private Integer code; // 消息 private String message; // 数据对象 private Object result; private Integer total; /** * 无参构造器 */ public ResultInfo() { super(); } public ResultInfo(Status status) { super(); this.code = status.code; this.message = status.message; } public ResultInfo result(Object result) { this.result = result; return this; } public ResultInfo message(String message) { this.message = message; return this; } public ResultInfo total(Integer total) { this.total = total; return this; } /** * 只返回状态,状态码,消息 * * @param code * @param message */ public ResultInfo(Integer code, String message) { super(); this.code = code; this.message = message; } /** * 只返回状态,状态码,数据对象 * * @param code * @param result */ public ResultInfo(Integer code, Object result) { super(); this.code = code; this.result = result; } /** * 返回全部信息即状态,状态码,消息,数据对象 * * @param code * @param message * @param result */ public ResultInfo(Integer code, String message, Object result) { super(); this.code = code; this.message = message; this.result = result; } }   Status.java package com.example.conf; /** * 枚举类对象 */ public enum Status { // 公共 SUCCESS(2000, "成功"), UNKNOWN_ERROR(9998,"未知异常"), SYSTEM_ERROR(9999, "系统异常"), INSUFFICIENT_PERMISSION(4003, "权限不足"), WARN(9000, "失败"), REQUEST_PARAMETER_ERROR(1002, "请求参数错误"), // 登录 LOGIN_EXPIRE(2001, "未登录或者登录失效"), LOGIN_CODE_ERROR(2002, "登录验证码错误"), LOGIN_ERROR(2003, "用户名不存在或密码错误"), LOGIN_USER_STATUS_ERROR(2004, "用户状态不正确"), LOGOUT_ERROR(2005, "退出失败,token不存在"), LOGIN_USER_NOT_EXIST(2006, "该用户不存在"), LOGIN_USER_EXIST(2007, "该用户已存在"); public int code; public String message; Status(int code, String message) { this.code = code; this.message = message; } } 附录:   一份详尽的yml配置文件(关于数据源的配置比较详尽): server: port: 8085 servlet: context-path: /test spring: #redis集群 redis: host: 127.0.0.1 port: 6379 timeout: 20000 # 集群环境打开下面注释,单机不需要打开 # cluster: # 集群信息 # nodes: xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx # #默认值是5 一般当此值设置过大时,容易报:Too many Cluster redirections # maxRedirects: 3 password: lyja application: name: test jedis: pool: max-active: 8 min-idle: 0 max-idle: 8 max-wait: -1 database: 0 autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure datasource: dynamic: #设置默认的数据源或者数据源组,默认值即为master primary: master strict: false datasource: master: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false username: root password: lyja # 数据源配置 druid: # druid连接池监控 stat-view-servlet: enabled: true url-pattern: /druid/* login-username: admin login-password: admin # 初始化时建立物理连接的个数 initial-size: 5 # 最大连接池数量 max-active: 30 # 最小连接池数量 min-idle: 5 # 获取连接时最大等待时间,单位毫秒 max-wait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 time-between-eviction-runs-millis: 60000 # 连接保持空闲而不被驱逐的最小时间 min-evictable-idle-time-millis: 300000 # 用来检测连接是否有效的sql,要求是一个查询语句 validation-query: select count(*) from dual # 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 test-while-idle: true # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 test-on-borrow: false # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 test-on-return: false # 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 pool-prepared-statements: false # 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。 max-pool-prepared-statement-per-connection-size: 50 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计 filters: stat,wall # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 connection-properties: druid.stat.mergeSql: true druid.stat.slowSqlMillis: 500 # 合并多个DruidDataSource的监控数据 use-global-data-source-stat: true filter: stat: log-slow-sql: true slow-sql-millis: 1000 merge-sql: true wall: config: multi-statement-allow: true servlet: multipart: # 开启 multipart 上传功能 enabled: true # 文件写入磁盘的阈值 file-size-threshold: 2KB # 最大文件大小 max-file-size: 200MB # 最大请求大小 max-request-size: 215MB mybatis-plus: configuration: map-underscore-to-camel-case: true auto-mapping-behavior: full log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:mapper/**/*Mapper.xml global-config: # 逻辑删除配置 db-config: # 删除前 logic-not-delete-value: 1 # 删除后 logic-delete-value: 0 logging: level: root: info com.example: debug   总结:   所有的面试题目都不是一成不变的,特别是像一线大厂,上面的资料只是给大家一个借鉴作用,最主要的是给自己增加知识的储备,有备无患。最后给大家分享Spring系列的学习笔记和面试题,包含spring面试题、spring cloud面试题、spring boot面试题、spring教程笔记、spring boot教程笔记、最新阿里巴巴开发手册(63页PDF总结)、2022年Java面试手册。一共整理了1184页PDF文档。私信博主(777)领取,祝大家更上一层楼!!!   原文作者:易水寒   原文出处:https://www.cnblogs.com/liuyj-top/p/12976396.html


摸鱼的真正奥秘!教你用正确的姿势摸鱼摸鱼,别名划水,一种神奇的存在,泛指在工作或者学习等所谓的办正事的时候去玩。关于如何摸鱼的探讨可谓从未停止过。时至今日,如何做到最完美的摸鱼,已经成为一种艺术。那么这次,九剑就来教微软,绝了大家好,我是九剑我的电脑,没错,就是电脑桌面那个图标,可以说是我们平常在桌面中打开最多的文件之一。无论你有多少快捷方式,或者其他骚操作,总是会用得到它。然而纵然微软这么多年来一直在真正的文学巨著!金瓶梅大家好,我是九剑。最近看了很多欧美动作大片,然而大多数只是图特效一乐。乐完之后实在索然无味,所以扒一扒我们的传统文化。三言二拍,神鬼志怪,侠义公案。华夏文明可谓源远流长,即便发展至一秒钟!找出你手机上所有小电影大家好,我是九剑。检索软件对于日常使用来说可谓及其重要,毕竟关键时刻找不到用不了的情况还是非常让人恼火的。说到检索,大名鼎鼎的Everything大家应该都用过,基本零延迟秒搜电脑双11性价比最高的55英寸智能电视HDR10认证4K屏人性化系统技术与价格是相互促进的,技术的成熟不仅可以提升产品品质,还能拉低产品价格,而价格的下探也会引发需求的增加,从而再激励技术发展。渐渐地,人们就可以花更少的钱享受更高品质的生活,比如智回忆杀!超级玛丽帝国战机三国战记全新体验大家好,我是九剑。目前手游占据游戏市场大半平台,玩的人是越来越多。手游品质也是越来越高,动不动就几个G,画面也确实牛逼。然而阿水觉得,相对于手机来说,以前那种带手柄的掌机才是永远的全球Q3手机出货量出炉,三星强势登顶,新品S21FE信息曝光最近市场调研机构IDC发布了今年第三季度全球手机出货量的数据统计,其中全球总出货量达到了3。312亿部,同比下滑高达6。7。该机构表示,全球供应链产能不足的影响是第三季度手机出货量价格小幅下调,新款荣威RX5ePLUS上市近日,我们从上汽荣威官网获悉,该品牌旗下插电混动车型新款荣威RX5ePLUS正式上市。新车共推出2款配置车型,售价区间为15。2816。28万元,相比老款车型,新车在售价方面有小幅标致508L2022款如何?年轻出行必备单品年轻人对于一台车的定义,无非运动和靓丽,同时还要品质感,有面子。所以,如今拥有运动格调的B级车,成为了越来越多年轻有为的消费人群首选。在B级车市场就有这样一台宝藏车,他就是标致502021高端冰箱攻略卡萨帝日立东芝西门子等品牌冰箱选购推荐朋友们好,本篇文章的主题是高端冰箱的推荐,既然是高端冰箱,那价格自然不必多说,分析的重点主要在于冰箱的功能和结构预算不足或者是租房使用的朋友可以看我的这篇文章冰箱选购知识2021性天衣无缝的焊接东风标致全新4008良心用料造就安全好车拆焊点检查是东风标致每个月都会有的一项工作。拆焊点比拆钢板难度要大,往往是钢板被撕破而焊点还是牢牢地连接在一起。而如此大费周章的进行检验,就是为了检测车辆的安全性,焊接的越牢固,汽
三星手机大面积系统崩溃,附解决方案前几天不少三星用户纷纷发现自己的手机出现了黑屏系统崩溃无法开机等现象,崩溃后的手机页面大概长这样看了下中招机型很多,三星GalaxyA系列如A60,三星S10S20等用户都有出现这三星S21Ultra渲染图曝光随着三星全新一代Note系列手机的正式发布,已经开始有越来越多的用户将目光转向了明年才会到来的S系列新机。近日,外媒对三星GalaxyS21系列渲染图曝光,让我们一起来看看吧。根据他带着全栈自研的中国智能汽车回来了以往,高配置往往也意味着高价格零跑C11彻底打破了这价值规则媲美50万元级豪华车的配置不到20万元就能享受零跑汽车是zui像做慈善的车企。这里的做慈善绝不是贬义词,恰恰相反,这是对有容乃大,远行伴侣地平线8号28英寸拉杆箱简评在拉杆箱的选购上,一般来说我们只需要根据自己的出行习惯进行选择即可,比如经常坐飞机短期出行的人比较适合选择20英寸行李箱,不需要带太多行李,又可以直接带上飞机对于国内外外长时间长途他带着全栈自研的中国智能汽车回来了以往,高配置往往也意味着高价格零跑C11彻底打破了这价值规则媲美50万元级豪华车的配置不到20万元就能享受零跑汽车是zui像做慈善的车企。这里的做慈善绝不是贬义词,恰恰相反,这是对越级de硬件素质与智能化能力在9月28日零跑C11的上市发布会上,被着重提到的一个词是越级,零跑也非常直白总结为是50万元级的期待,不到20万元就能实现。零跑汽车CEO朱江明标榜C11很可能是20万元以内zu智能豪华美学三大越级实力此外,零跑C11搭载的智能驾驶辅助解决方案LeapPilot3。0也给试驾者带来了不同寻常的科技体验,采用两颗全自研凌芯01智能驾驶芯片,算力达到8。4T,是现有MobileyeE安全可靠一物两用?德施曼小嘀Q3M智能锁给你答案序对于我个人来说,是一个喜欢新鲜事物,并且折腾心比较大的人,所以为了解决日常生活中每天上下班开门锁门的问题,早早就安装使用上了指纹智能锁,果然,智能锁安装后,上下班后进家门就不再掏客厅氛围由你任意掌控?达伦智能吸顶灯带来不一样的体验序随着科技进步,越来越多的家庭在装修时候把智能家居纳入了装修范围,比如在硬装和软装时候都优先考虑到智能家居的使用考虑,从而在布线走线不同空间内的设计提前做好规划,这样才能让智能家居双11来临AMD性价比游戏笔记本如何选择?看完分析有答案前言在一年一度的购物盛会双11来临之际,想必很多小伙伴开始准备购置不少物品,包括游戏笔记本,但购买之前,很多人不知道如何下手,基于手头多台笔记本使用和购买经验,在这里给大家聊聊关于人工智能脑机接口让我们距离增强人类越来越近资本实验室今日创新观察聚焦前沿科技创新与传统产业升级前段时间,一则新闻引发了广泛争议国内一所小学利用头环来监控孩子的脑电波,以判断孩子上课是否走神。暂且不论该事件是否是一场打着高科