MyBatis-plus自動生產

目錄

簡介

代碼結構

Mapper

Service

ServiceImpl

編寫模板

模板的入參

配置類

yml讀取配置

代碼生成器


簡介

Mybatis-plus是在Mybatis上新增了一些工具,只有增加沒有修改,導入Mybatis-plus的包,原來的代碼不受影響。使用新的寫法可以去享受新的工具帶來的福利。以下代碼省略部分import。

代碼結構

主要在以下幾個地方有些變化

Mapper

package zs.mapper;

import zs.entity.Food;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 * 食品表 Mapper 接口
 * </p>
 *
 * @author 張爍
 * @since 2019-11-26
 */
public interface FoodMapper extends BaseMapper<Food> {

}

Service

package zs.service;

import zs.entity.Food;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 * 食品表 服務類
 * </p>
 *
 * @author 張爍
 * @since 2019-11-26
 */

public interface IFoodService extends IService<Food> {

}

ServiceImpl

package zs.service.impl;

import zs.entity.Food;
import zs.mapper.FoodMapper;
import zs.service.IFoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 食品表 服務實現類
 * </p>
 *
 * @author 張爍
 * @since 2019-11-26
 */
@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements IFoodService {

}

編寫模板

包的這個位置有默認的模板,舉個例子

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};

/**
* ${table.comment!} Mapper 接口
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
    interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
    public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

    }
</#if>

模板的入參

${}裏不是自己傳進去的map,查看源碼

裏面封裝了幾個模板的實現,我用的是Freemarker,入參是他們父類AbstractTemplateEngine裏的getObjectMap(TableInfo tableInfo)方法整理的,key值裏面寫死了,需要的話想辦法重寫。

配置類

yml讀取配置

我把裏面的參數提出來,爲了以後更方便的配置,所以去Springboot的源碼裏把它讀取yml的部分拿出來根據我自己的需求改寫。

import cn.hutool.json.JSONObject;
import org.springframework.boot.env.YamlPropertySourceLoader;


/**
 * 讀取yml文件的工具類
 * @author 張爍
 */
public class YmlReaderUtil {

    private static MapPropertySource mpropertySource;

    static {
        //加載springboot的yaml解析器
        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
        //配置源
        Resource resource = new AbstractResource() {
            @Override
            public String getDescription() {
                return "";
            }

            /**
             * 拼接輸入流
             */
            @Override
            public InputStream getInputStream() throws IOException {
                String projectPath = System.getProperty("user.dir");
                return new FileInputStream(projectPath + "/src/main/resources/config/" + "codeGenerator.yml");
            }
        };

        List<PropertySource<?>> propertySourceList = new ArrayList<>();
        try {
            propertySourceList = yamlPropertySourceLoader.load("codeGenerator.yml", resource);
        } catch (IOException e) {
            System.err.println("讀取失敗");
            e.printStackTrace();
        }
        mpropertySource=(MapPropertySource)propertySourceList.get(0);
    }


    public static JSONObject getMap(){
        JSONObject json=JSONUtil.parseObj(mpropertySource.getSource());
        return json;
    }
}

輸出的就是yml的json格式

代碼生成器

調用上面的工具


import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.generator.AutoGenerator;

public class CodeGenerator {

    /**
     * 表名
     */
    private static final String table = YmlReaderUtil.getMap().getStr("tableName");

    public static void main(String[] args) {

        JSONObject json = YmlReaderUtil.getMap();

        // 代碼生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + json.getStr("outputDir"));
        gc.setAuthor(json.getStr("author"));
        gc.setOpen(false);
        // gc.setSwagger2(true); 實體屬性 Swagger2 註解
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(json.getStr("datasource.url"));
        dsc.setDriverName(json.getStr("datasource.driver-class-name"));
        dsc.setUsername(json.getStr("datasource.username"));
        dsc.setPassword(json.getStr("datasource.password").substring(1));
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(json.getStr("parent"));
        mpg.setPackageInfo(pc);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定義輸出模板
        templateConfig.setService(json.getStr("ftl.service"));
        templateConfig.setController(json.getStr("ftl.controller"));
        templateConfig.setServiceImpl(json.getStr("ftl.serviceImpl"));
        templateConfig.setMapper(json.getStr("ftl.mapperJava"));
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        //自定義包名
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent(json.getStr("parent"));
        mpg.setPackageInfo(packageConfig);

        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        injectionConfig.initMap();
        mpg.setCfg(injectionConfig);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setEntityTableFieldAnnotationEnable(false);
        // 寫於父類中的公共字段
        strategy.setInclude(table);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章