MyBatisPlus AutoGenrator代码自动生成

1. 使用MyBatisPlus AutoGenrator注意数据库表字段最好用下划线分格,生成的Bean类才会是驼峰式的

2. 在/src/main/resources中加入Mybatis-Plus.properties配置文件

#此处为本项目src所在路径(代码生成器输出路径)
OutputDir=E:/workspace/ssmp-crud-2/src/main/java
OutputDirXml=E:/workspace/ssmp-crud-2/src/main/resources
#数据库表名(此处切不可为空,如果为空,则默认读取数据库的所有表名)
tableName=tbl_emp
#装代码的文件夹名
className=empMsg
#设置作者
author=Yifan
#正常情况下,下面的代码无需修改!!!!!!!!!!
#自定义包路径
parent=com.atguigu.crud
#数据库地址
url=jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8
userName=root
password=123456

3. Java代码中直接运行

public class MpGenerator1{
    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        final ResourceBundle rb = ResourceBundle.getBundle("Mybatis-Plus");
        
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        gc.setEnableCache(true);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setAuthor(rb.getString("author"));
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);
        
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        /*dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("转换类型:" + fieldType);
                return super.processTypeConvert(fieldType);
            }
        });*/
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUrl(rb.getString("url"));
        dsc.setUsername(rb.getString("userName"));
        dsc.setPassword(rb.getString("password"));
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
        // strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[] {rb.getString("tableName")}); // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定义实体父类
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定义实体,公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定义 mapper 父类
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 service 父类
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 service 实现类父类
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 controller 父类
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【实体】是否生成字段常量(默认 false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型(默认 false)
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);
        
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent"));
        // pc.setModuleName("tbldept");//模块名称,单独生成模块时使用!!!!!!!!!!!
        pc.setController("controller."+rb.getString("className"));
        pc.setService("service."+rb.getString("className"));
        pc.setServiceImpl("service."+rb.getString("className")+".impl");
        pc.setEntity("bean."+rb.getString("className"));
        pc.setMapper("dao."+rb.getString("className"));
        mpg.setPackageInfo(pc);
        
        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };
        
        // 自定义 xxList.jsp 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        /*focList.add(new FileOutConfig("/template/list.jsp.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "E:/workspace/ssmp-crud2/src/main/webapp/WEB-INF/" + tableInfo.getEntityName() + ".jsp";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);*/
        
        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+"/mapper/" +rb.getString("className") + "/" + tableInfo.getEntityName() + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        
        // 关闭默认 xml 生成,调整生成 至 根目录
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);
        
        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        // mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();
    }
}

MyBatisPlus是一个基于MyBatis的Java快速开发框架,它提供了一系列便捷的方法,简化了数据持久层的操作,包括实体生成、CRUD操作、数据库迁移等。其中,代码自动生成MyBatisPlus的一大亮点,它能根据数据库表结构自动生成对应的Java实体(Pojo)、Mapper接口和XML文件。 具体步骤如下: 1. **配置Generator工具**:在MyBatisPlus的配置文件中,通常是在`GlobalConfig`或`BaseMapper`中,你可以配置代码生成器的相关信息,如包名、文件路径、实体命名规则等。 ```java // 在全局配置中 public GlobalConfig global = new GlobalConfig(); global.setDbType("mysql"); // 数据库型 global.setOutputDir("src/main/java"); // 生成的文件目录 global.setAuthor("your_name"); // 作者名称 global.setProjectName("your_project"); // 项目名称 ``` 2. **启用代码生成**:调用`generator.generate()`方法,传入表名列表,MyBatisPlus会扫描这些表并生成相应的代码。 ```java List<String> tableNameList = Arrays.asList("your_table_1", "your_table_2"); MysqlGlobalConfig mysqlConfig = new MysqlGlobalConfig(); // 如果是MySQL数据库 mysqlConfig.setTablePrefix("your_prefix_"); // 表前缀 generator.generate(tableNameList, mysqlConfig); ``` 3. **查看生成的代码**:在指定的目录下,你会看到生成的实体(例如`YourTableName.java`)、Mapper接口(例如`YourTableNameMapper.java`)以及对应的XML映射文件。 MyBatisPlus的代码自动生成能够极大地提高开发效率,但需要注意的是,生成的代码仅为初始版本,可能需要根据实际业务需求进行调整和优化。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值