建立项目:
选择spring Initializr,注意要选择jdk,使用默认的spring.io这 样就不用再去写pom文件了
输入项目名称:
选择Spring Web
目录结构:
java
表结构以下mysql
id | name | age | |
---|---|---|---|
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 |
其对应的数据库 Schema 脚本以下:git
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) );
其对应的数据库 Data 脚本以下:github
DELETE FROM user; 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');
**注意:把主键id设为自动递增**
web
引入 Spring Boot Starter 父工程:spring
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.5.RELEASE</version> <relativePath/> </parent>
引入 spring-boot-starter
、spring-boot-starter-test
、mybatis-plus-boot-starter
、lombok
、druid
、mysql-connector-java
、mybatis-plus-generator
、 velocity-engine-core
、freemarker
等依赖:sql
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!-- lombok插件 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- 代码生成器与模板引擎 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.0</version> </dependency> <!-- 模板引擎 依赖 Velocity(默认) --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency> <!-- Freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> </dependency> <!-- MyBatis-Plus 插件 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <!-- Mysql 链接插件 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 引入阿里数据库链接池 --> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.1</version> </dependency></dependencies>
把resource包下的application.properties复制一份再粘贴名字改为application.yml,在 application.yml
配置文件中添加 mysql 数据库的相关配置:数据库
# 端口配置 server: port: 8080 servlet: context-path: / # 数据源配置 spring: application: name: springboot-mybatis-plus datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC type: com.alibaba.druid.pool.DruidDataSource username: root password: root jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 # Mybatis-Plus配置 mybatis-plus: # 若是是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml # 若是是放在resource目录 classpath:/mapper/*Mapper.xml mapper-locations: classpath*:com/frame/**/**.xml,classpath*:mapper/*.xml #实体扫描,多个package用逗号或者分号分隔 typeAliasesPackage: com.frame.**.entity,com.frame.**.dto global-config: #刷新mapper 调试神器 db-config: #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局惟一ID (数字类型惟一ID)", 3:"全局惟一ID UUID"; id-type: UUID #字段策略 IGNORED:"忽略判断" NOT_NULL:"非 NULL 判断") NOT_EMPTY:"非空判断" field-strategy: NOT_EMPTY #数据库类型 db-type: MYSQL #逻辑删除配置 logic-delete-value: 1 # 逻辑已删除值(默认为 1) logic-not-delete-value: 0 # 逻辑未删除值(默认为 0) #驼峰下划线转换 column-underline: false #数据库大写下划线转换 # capital-mode: true refresh: true configuration: # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的相似映射 map-underscore-to-camel-case: true # 若是查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段 call-setters-on-nulls: true cache-enabled: false #配置JdbcTypeForNull, oracle数据库必须配置 jdbc-type-for-null: 'null' # 这个配置会将执行的sql打印出来,在开发或测试的时候能够用 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl database-id: mysql
AutoGenerator 是 MyBatis-Plus 的代码生成器,经过 AutoGenerator 能够快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码apache
/** * <p> * 读取控制台内容 * </p> */ 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.isNotBlank(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("wulongbo"); gc.setOpen(false); // gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // pc.setModuleName(scanner("模块名")); pc.setParent("com.mybatis.plus"); 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<FileOutConfig> 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("调用默认方法建立的目录,自定义目录用"); if (fileType == FileType.MAPPER) { // 已经生成 mapper 文件判断存在,不想从新生成返回 false return !new File(filePath).exists(); } // 容许生成模板文件 return true; } }); */ 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("你本身的父类实体,没有就不用设置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 // strategy.setSuperControllerClass("你本身的父类控制器,没有就不用设置!"); // 写于父类中的公共字段 // strategy.setSuperEntityColumns("id"); //删掉,不删的话实体类没有id strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); // strategy.setTablePrefix("sys" + "_");//去掉表前缀 strategy.setTablePrefix("tbl" + "_");//去掉表前缀 mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); }
执行 main 方法控制台输入模块表名【user】回车自动生成对应项目目录,目录结构以下:api
必需要在springboot启动类上加上扫包注解@MapperScan(basePackages = "com.xxx.xxx"),或者在Dao层上加上@Mapper 或 @Repository注解来注入Mapper文件,在这里选用主程序扫包的方式注入
install一下,而后启动项目,若是启动失败,则须要跳过测试,在pom文件中添加配置跳过测试
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> <!--添加配置跳过测试--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> <configuration> <skipTests>true</skipTests> </configuration> </plugin> </plugins></build>
启动成功后如图,至此Springboot集成Mybatis-Plus就OK了
【参考文档】Mybatis-Plus官网连接:Mybatis-Plus官网因为公司性质,全部代码加密了,外网github上传不了因此这里就不提供github连接了。