還在手寫CRUD代碼?這款開源框架助你解放雙手

相信不少朋友在項目中使用的ORM框架都是MyBatis,若是單用MyBatis來操做數據庫的話,須要手寫不少單表查詢的SQL實現。這時候咱們每每會選擇一個加強工具來實現這些單表CRUD操做,這裏推薦一款好用的工具MyBatis-Plus!php

MyBatis-Plus簡介

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的加強工具,在 MyBatis 的基礎上只作加強不作改變,爲簡化開發、提升效率而生。MyBatis-Plus 提供了代碼生成器,能夠一鍵生成controller、service、mapper、model、mapper.xml代碼,同時提供了豐富的CRUD操做方法,助咱們解放雙手!前端

MyBatis-Plus集成

首先咱們須要在SpringBoot項目中集成MyBatis-Plus,以後咱們再詳細介紹它的使用方法!java

  • pom.xml中添加相關依賴,主要是MyBatis-Plus、MyBatis-Plus Generator和Velocity模板引擎;mysql

<dependencies>
    <!--Mybatis-Plus依賴-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.2</version>
    </dependency>
    <!--Mybatis-Plus代碼生成器-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.3.2</version>
    </dependency>
    <!--Velocity模板生成引擎-->
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.2</version>
    </dependency>
</dependencies>
  • 在SpringBoot配置文件application.yml添加以下配置,配置好數據源和MyBatis-Plus;spring

spring:
  datasource:
    urljdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
mybatis-plus:
  mapper-locations: classpath:/mapper/**/*.xml #指定mapper.xml路徑
  global-config:
    db-config:
      id-type: auto #全局默認主鍵類型設置爲自增
  configuration:
    auto-mapping-behavior: partial #只對非嵌套的 resultMap 進行自動映射
    map-underscore-to-camel-case: true #開啓自動駝峯命名規則映射
  • 添加MyBatis-Plus的Java配置,使用@MapperScan註解配置好須要掃碼的Mapper接口路徑,MyBatis-Plus自帶分頁功能,須要配置好分頁插件PaginationInterceptorsql

/**
 * MyBatis配置類
 * Created by macro on 2019/4/8.
 */
@Configuration
@MapperScan("com.macro.mall.tiny.modules.*.mapper")
public class MyBatisConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }}

代碼生成器

MyBatis-Plus 提供了代碼生成器,能夠一鍵生成controller、service、mapper、model、mapper.xml代碼,很是方便!typescript

  • 首先咱們建立代碼生成器類MyBatisPlusGenerator,直接運行其main方法便可生成相關代碼;數據庫

/**
 * MyBatisPlus代碼生成器 * Created by macro on 2020/8/20.
 */public class MyBatisPlusGenerator {    public static void main(String[] args) {        String projectPath = System.getProperty("user.dir") + "/mall-tiny-plus";
        String moduleName = scanner("模塊名");
        String[] tableNames = scanner("表名,多個英文逗號分割").split(",");
        // 代碼生成器        AutoGenerator autoGenerator = new AutoGenerator();        autoGenerator.setGlobalConfig(initGlobalConfig(projectPath));        autoGenerator.setDataSource(initDataSourceConfig());        autoGenerator.setPackageInfo(initPackageConfig(moduleName));        autoGenerator.setCfg(initInjectionConfig(projectPath, moduleName));        autoGenerator.setTemplate(initTemplateConfig());        autoGenerator.setStrategy(initStrategyConfig(tableNames));        autoGenerator.setTemplateEngine(new VelocityTemplateEngine());        autoGenerator.execute();
    }    /**     * 讀取控制檯內容信息     */    private static String scanner(String tip) {        Scanner scanner = new Scanner(System.in);
        System.out.println(("請輸入" + tip + ":"));
        if (scanner.hasNext()) {
            String next = scanner.next();
            if (StrUtil.isNotEmpty(next)) {
                return next;
            }        }        throw new MybatisPlusException("請輸入正確的" + tip + "!");
    }    /**     * 初始化全局配置     */    private static GlobalConfig initGlobalConfig(String projectPath) {        GlobalConfig globalConfig = new GlobalConfig();        globalConfig.setOutputDir(projectPath + "/src/main/java");
        globalConfig.setAuthor("macro");
        globalConfig.setOpen(false);
        globalConfig.setSwagger2(true);
        globalConfig.setBaseResultMap(true);
        globalConfig.setFileOverride(true);
        globalConfig.setDateType(DateType.ONLY_DATE);        globalConfig.setEntityName("%s");
        globalConfig.setMapperName("%sMapper");
        globalConfig.setXmlName("%sMapper");
        globalConfig.setServiceName("%sService");
        globalConfig.setServiceImplName("%sServiceImpl");
        globalConfig.setControllerName("%sController");
        return globalConfig;
    }    /**     * 初始化數據源配置     */    private static DataSourceConfig initDataSourceConfig() {        Props props = new Props("generator.properties");
        DataSourceConfig dataSourceConfig = new DataSourceConfig();        dataSourceConfig.setUrl(props.getStr("dataSource.url"));
        dataSourceConfig.setDriverName(props.getStr("dataSource.driverName"));
        dataSourceConfig.setUsername(props.getStr("dataSource.username"));
        dataSourceConfig.setPassword(props.getStr("dataSource.password"));
        return dataSourceConfig;
    }    /**     * 初始化包配置     */    private static PackageConfig initPackageConfig(String moduleName) {        Props props = new Props("generator.properties");
        PackageConfig packageConfig = new PackageConfig();        packageConfig.setModuleName(moduleName);        packageConfig.setParent(props.getStr("package.base"));
        packageConfig.setEntity("model");
        return packageConfig;
    }    /**     * 初始化模板配置     */    private static TemplateConfig initTemplateConfig() {        TemplateConfig templateConfig = new TemplateConfig();        //能夠對controller、service、entity模板進行配置        //mapper.xml模板需單獨配置        templateConfig.setXml(null);        return templateConfig;
    }    /**     * 初始化策略配置     */    private static StrategyConfig initStrategyConfig(String[] tableNames) {        StrategyConfig strategyConfig = new StrategyConfig();        strategyConfig.setNaming(NamingStrategy.underline_to_camel);        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);
        //當表名中帶*號時能夠啓用通配符模式        if (tableNames.length == 1 && tableNames[0].contains("*")) {
            String[] likeStr = tableNames[0].split("_");
            String likePrefix = likeStr[0] + "_";
            strategyConfig.setLikeTable(new LikeTable(likePrefix));        } else {
            strategyConfig.setInclude(tableNames);        }        return strategyConfig;
    }    /**     * 初始化自定義配置     */    private static InjectionConfig initInjectionConfig(String projectPath, String moduleName) {        // 自定義配置        InjectionConfig injectionConfig = new InjectionConfig() {            @Override            public void initMap() {                // 可用於自定義屬性            }        };        // 模板引擎是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/" + moduleName
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }        });        injectionConfig.setFileOutConfigList(focList);        return injectionConfig;
    }}
  • 而後在resources目錄下添加配置文件generator.properties,添加代碼生成器的數據源配置及存放業務代碼的基礎包名稱;apache

dataSource.url=jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
dataSource.driverName=com.mysql.cj.jdbc.DriverdataSource.username=rootdataSource.password=rootpackage.base=com.macro.mall.tiny.modules
  • 細心的朋友能夠發現MyBatisPlusGenerator中不少配置代碼都沒添加註釋,其實MyBatis-Plus源碼中的中文註釋很是完善,只需查看源碼便可,這裏摘抄一段DataSourceConfig中的源碼;mybatis

/**
 * 數據庫配置
 *
 * @author YangHu, hcl
 * @since 2016/8/30
 */
@Data
@Accessors(chain = true)
public class DataSourceConfig {
    /**
     * 數據庫信息查詢
     */
    private IDbQuery dbQuery;
    /**
     * 數據庫類型
     */
    private DbType dbType;
    /**
     * PostgreSQL schemaName
     */
    private String schemaName;
    /**
     * 類型轉換
     */
    private ITypeConvert typeConvert;
    /**
     * 關鍵字處理器
     * @since 3.3.2
     */
    private IKeyWordsHandler keyWordsHandler;
    /**
     * 驅動鏈接的URL
     */
    private String url;
    /**
     * 驅動名稱
     */
    private String driverName;
    /**
     * 數據庫鏈接用戶名
     */
    private String username;
    /**
     * 數據庫鏈接密碼
     */
    private String password;
        //省略若干代碼......
}
  • 代碼生成器支持兩種模式,一種生成單表的代碼,好比只生成pms_brand表代碼能夠先輸入pms,後輸入pms_brand

還在手寫CRUD代碼?這款開源框架助你解放雙手


  • 生成單表代碼結構一覽;

還在手寫CRUD代碼?這款開源框架助你解放雙手


  • 另外一種直接生成整個模塊的代碼,須要帶通配符*,好比生成ums模塊代碼能夠先輸入ums,後輸入ums_*

還在手寫CRUD代碼?這款開源框架助你解放雙手


  • 生成整個模塊代碼結構一覽。

還在手寫CRUD代碼?這款開源框架助你解放雙手


自定義生成模板

MyBatis-Plus 使用模板引擎來生成代碼,支持 Velocity(默認)、Freemarker、Beetl模板引擎,這裏以Velocity爲了來介紹下如何自定義生成模板。

  • 首先咱們能夠從 MyBatis-Plus Generator依賴包的源碼中找到默認模板,拷貝到項目的resources/templates目錄下;

還在手寫CRUD代碼?這款開源框架助你解放雙手


  • MyBatisPlusGenerator類中對TemplateConfig進行配置,配置好各個模板的路徑;

/**
 * MyBatisPlus代碼生成器
 * Created by macro on 2020/8/20.
 */
public class MyBatisPlusGenerator {
        /**
     * 初始化模板配置
     */
    private static TemplateConfig initTemplateConfig() {
        TemplateConfig templateConfig = new TemplateConfig();
        //能夠對controller、service、entity模板進行配置
        templateConfig.setEntity("templates/entity.java");
        templateConfig.setMapper("templates/mapper.java");
        templateConfig.setController("templates/controller.java");
        templateConfig.setService("templates/service.java");
        templateConfig.setServiceImpl("templates/serviceImpl.java");
        //mapper.xml模板需單獨配置
        templateConfig.setXml(null);
        return templateConfig;
    }
}
  • 對模板進行定製,在定製過程當中咱們能夠發現不少內置變量,用於輸出到模板中去,這裏以service.java.vm模板爲例子,好比packagetable這些變量;

package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/** * <p> * $!{table.comment} 服務類 * </p> * * @author ${author}
 * @since ${date}
 */#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#elsepublic interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}#end
  • 搞懂這些變量從哪來的,對咱們定製模板頗有幫助,其實這些變量都來着於AbstractTemplateEnginegetObjectMap方法,具體變量做用能夠參考源碼。

/**
 * 模板引擎抽象類 * * @author hubin * @since 2018-01-10
 */public abstract class AbstractTemplateEngine {        /**         * 渲染對象 MAP 信息         *         * @param tableInfo 表信息對象         * @return ignore
         */        public Map<String, Object> getObjectMap(TableInfo tableInfo) {            Map<String, Object> objectMap = new HashMap<>(30);
            ConfigBuilder config = getConfigBuilder();
            if (config.getStrategyConfig().isControllerMappingHyphenStyle()) {
                objectMap.put("controllerMappingHyphenStyle"config.getStrategyConfig().isControllerMappingHyphenStyle());
                objectMap.put("controllerMappingHyphen", StringUtils.camelToHyphen(tableInfo.getEntityPath()));
            }            objectMap.put("restControllerStyle"config.getStrategyConfig().isRestControllerStyle());
            objectMap.put("config"config);
            objectMap.put("package"config.getPackageInfo());
            GlobalConfig globalConfig = config.getGlobalConfig();
            objectMap.put("author", globalConfig.getAuthor());
            objectMap.put("idType", globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString());
            objectMap.put("logicDeleteFieldName"config.getStrategyConfig().getLogicDeleteFieldName());
            objectMap.put("versionFieldName"config.getStrategyConfig().getVersionFieldName());
            objectMap.put("activeRecord", globalConfig.isActiveRecord());
            objectMap.put("kotlin", globalConfig.isKotlin());
            objectMap.put("swagger2", globalConfig.isSwagger2());
            objectMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            objectMap.put("table", tableInfo);
            objectMap.put("enableCache", globalConfig.isEnableCache());
            objectMap.put("baseResultMap", globalConfig.isBaseResultMap());
            objectMap.put("baseColumnList", globalConfig.isBaseColumnList());
            objectMap.put("entity", tableInfo.getEntityName());
            objectMap.put("entitySerialVersionUID"config.getStrategyConfig().isEntitySerialVersionUID());
            objectMap.put("entityColumnConstant"config.getStrategyConfig().isEntityColumnConstant());
            objectMap.put("entityBuilderModel"config.getStrategyConfig().isEntityBuilderModel());
            objectMap.put("chainModel"config.getStrategyConfig().isChainModel());
            objectMap.put("entityLombokModel"config.getStrategyConfig().isEntityLombokModel());
            objectMap.put("entityBooleanColumnRemoveIsPrefix"config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix());
            objectMap.put("superEntityClass", getSuperClassName(config.getSuperEntityClass()));
            objectMap.put("superMapperClassPackage"config.getSuperMapperClass());
            objectMap.put("superMapperClass", getSuperClassName(config.getSuperMapperClass()));
            objectMap.put("superServiceClassPackage"config.getSuperServiceClass());
            objectMap.put("superServiceClass", getSuperClassName(config.getSuperServiceClass()));
            objectMap.put("superServiceImplClassPackage"config.getSuperServiceImplClass());
            objectMap.put("superServiceImplClass", getSuperClassName(config.getSuperServiceImplClass()));
            objectMap.put("superControllerClassPackage", verifyClassPacket(config.getSuperControllerClass()));
            objectMap.put("superControllerClass", getSuperClassName(config.getSuperControllerClass()));
            return Objects.isNull(config.getInjectionConfig()) ? objectMap : config.getInjectionConfig().prepareObjectMap(objectMap);
        }}

CRUD操做

MyBatis-Plus的強大之處不止在於它的代碼生成功能,還在於它提供了豐富的CRUD方法,讓咱們實現單表CRUD幾乎不用手寫SQL實現!

  • 咱們以前生成的PmsBrandMapper接口因爲繼承了BaseMapper接口,直接擁有了各類CRUD方法;

/**
 * <p>
 * 品牌表 Mapper 接口
 * </p>
 *
 * @author macro
 * @since 2020-08-20
 */
public interface PmsBrandMapper extends BaseMapper<PmsBrand{
}
  • 咱們來看下BaseMapper中的方法,是否是基本能夠知足咱們的平常所需了;

還在手寫CRUD代碼?這款開源框架助你解放雙手


  • 咱們以前生成的PmsBrandService接口因爲繼承了IService接口,也擁有了各類CRUD方法;

/**
 * <p>
 * 品牌表 服務類
 * </p>
 *
 * @author macro
 * @since 2020-08-20
 */
public interface PmsBrandService extends IService<PmsBrand{
}
  • 能夠看下比BaseMapper中的更加豐富;

還在手寫CRUD代碼?這款開源框架助你解放雙手


  • 有了這些IServiceBaseMapper中提供的這些方法,咱們單表查詢就幾乎不用手寫SQL實現了,使用MyBatis-Plus實現之前PmsBrandController的方法更輕鬆了!

/**
 * <p>
 * 品牌表 前端控制器
 * </p>
 *
 * @author macro
 * @since 2020-08-20
 */
@Api(tags = "PmsBrandController", description = "商品品牌管理")
@RestController
@RequestMapping("/brand")
public class PmsBrandController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
    @Autowired
    private PmsBrandService brandService;
    @ApiOperation("獲取全部品牌列表")
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<PmsBrand>> getBrandList() {
        return CommonResult.success(brandService.list());
    }    @ApiOperation("添加品牌")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
        CommonResult commonResult;        boolean result = brandService.save(pmsBrand);        if (result) {
            commonResult = CommonResult.success(pmsBrand);            LOGGER.debug("createBrand success:{}", pmsBrand);
        } else {
            commonResult = CommonResult.failed("操做失敗");
            LOGGER.debug("createBrand failed:{}", pmsBrand);
        }        return commonResult;
    }    @ApiOperation("更新指定id品牌信息")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateBrand(@RequestBody PmsBrand pmsBrand) {
        CommonResult commonResult;        boolean result = brandService.updateById(pmsBrand);        if (result) {
            commonResult = CommonResult.success(pmsBrand);            LOGGER.debug("updateBrand success:{}", pmsBrand);
        } else {
            commonResult = CommonResult.failed("操做失敗");
            LOGGER.debug("updateBrand failed:{}", pmsBrand);
        }        return commonResult;
    }    @ApiOperation("刪除指定id的品牌")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult deleteBrand(@PathVariable("id") Long id) {
        boolean result = brandService.removeById(id);        if (result) {
            LOGGER.debug("deleteBrand success :id={}", id);
            return CommonResult.success(null);
        } else {
            LOGGER.debug("deleteBrand failed :id={}", id);
            return CommonResult.failed("操做失敗");
        }    }    @ApiOperation("分頁查詢品牌列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1")
                                                        @ApiParam("頁碼") Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "3")
                                                        @ApiParam("每頁數量") Integer pageSize) {
        Page<PmsBrand> page = new Page<>(pageNum, pageSize);        Page<PmsBrand> pageResult = brandService.page(page);        return CommonResult.success(CommonPage.restPage(pageResult));
    }    @ApiOperation("獲取指定id的品牌詳情")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {
        return CommonResult.success(brandService.getById(id));    }}
相關文章
相關標籤/搜索