SpringBoot整合MybatisPlus的簡單教程(簡單整合)

最近在研究springboot,順便就會看看數據庫鏈接這一塊的知識 ,因此當我發現有通用Mapper和MybatisPlus這兩款網絡上比較火的簡化mybatis開發的優秀軟件以後。就都想試一下,看看哪一款比較適合本身。
<!-- 這是mysql的依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- 這是lombok的依賴 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 這是mybatis-plus依賴 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!-- 這是mybatis-plus的代碼自動生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!-- 這是模板引擎依賴 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
  • 須要對application.yml進行相關的配置。
#端口號
    server:
      port: 8088
    #數據庫的配置信息
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/*** #本身的數據庫名稱
        username: root
        password: 123456
    mybatis:
      #開啓駝峯命名法
      configuration:
        map-underscore-to-camel-case: true
    mybatis-plus:
      # xml地址
      mapper-locations: classpath:mapper/*Mapper.xml
      # 實體掃描,多個package用逗號或者分號分隔
      type-aliases-package: ***   #本身的實體類地址
      configuration:
        # 這個配置會將執行的sql打印出來,在開發或測試的時候能夠用
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  • 自動生成模塊的方法,在相應的位置上添加上本身的一些包名就能夠運行生成相應的Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼。
public class CodeGenerator {

    /**
     * <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.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("jobob");
        gc.setOpen(false);
        // gc.setSwagger2(true); 實體屬性 Swagger2 註解
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/***?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("***");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //這裏有個模塊名的配置,能夠註釋掉不用。
//        pc.setModuleName(scanner("模塊名"));
        pc.setParent("com.zhouxiaoxi.www");
        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("調用默認方法建立的目錄");
                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);
        //數據庫表字段映射到實體的命名策略, 未指定按照 naming 執行
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //自定義繼承的Entity類全稱,帶包名
//        strategy.setSuperEntityClass("***");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //自定義繼承的Controller類全稱,帶包名
//        strategy.setSuperControllerClass("***");
        strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
        //自定義基礎的Entity類,公共字段(可添加更多)
//        strategy.setSuperEntityColumns("id");
        //駝峯轉連字符
        strategy.setControllerMappingHyphenStyle(true);
        //表前綴
//        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
  • 在生成的controller裏面添加對應的方法啓動就能夠正常進行訪問了。

    clipboard.png

固然還須要在 Spring Boot 啓動類中添加 @MapperScan 註解,掃描 Mapper 文件夾:java

@SpringBootApplication
@MapperScan("***.*.mapper") //對應你的mapper存放的地址
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(QuickStartApplication.class, args);
    }

}
相關文章
相關標籤/搜索