MyBatis-plus+注解形式实现项目与数据库绑定动态更新

前言:在自己电脑上使用mybatis-plus生成映射数据库表的实体类,将项目上传到服务器启动时根据实体类自动创建、更新相应的数据库表,这样做的目的是使得在自己电脑上创建数据库表后不用再到服务器去创建

 实现思路:

  1. 使用mybatis-plus生成实体类
  2. 在生成实体类的时候获取类字段信息并通过注解的形式写入到实体类里面去
  3. 在服务器启动项目的时候获取项目的所有实体类与数据库所有表进行对比,解析实体类上注解信息,写入特定的类用于将数据库没有对应的表进行创建

详细步骤

1.配置mybatis-plus自动生成代码

   依赖mybatis-plus   

<!-- mp 依赖 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>2.3</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatisplus-spring-boot-starter</artifactId>
    <version>1.0.5</version>
</dependency>
<!--生成代码模板引擎-->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>
<!-- 模板引擎 -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>

 配置

mybatis-plus:
  mapper-locations: classpath*:/mapper/*/*Mapper.xml
  global-config:
    id-type: 3
    field-strategy: 2
    db-column-underline: true
    refresh-mapper: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

 代码生成器

MpGenerator.java

import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.toolkit.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

public class MpGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public 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 + "!");
    }

    private int type;



    public PackageConfig getPackageConfig() {
        PackageConfig pc = new PackageConfig();
        if (type == 3) {
            pc.setParent("com.wdz.tofs");
        } else {
            pc.setParent("com.wdz");
        }
        pc.setModuleName(scanner("模块名"));
        pc.setEntity("entity");
        pc.setController(null);
        return pc;
    }
    /**
     * 获取表字段信息
     */
    public ResultSetMetaData getMetaData(DataSourceConfig dsc,String tableName){
        Connection connection = dsc.getConn();
        try {
            try (PreparedStatement preparedStatement = connection.prepareStatement("select * from " + tableName)) {
                return preparedStatement.executeQuery().getMetaData();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();
        MpGenerator mpGenerator = new MpGenerator();
        // 选择 freemarker 引擎,默认 Veloctiy
        //mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOpen(false);//完成后不打开文件夹
        gc.setAuthor("autor");
        String oPath = System.getProperty("user.dir");//得到当前项目的路径
        gc.setOutputDir(oPath + "/core_database/src/main/java/");   //生成文件输出根目录
        gc.setFileOverride(false);// 是否覆盖同名文件,默认是false
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setIdType(IdType.UUID);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
                if (fieldType.equals("datetime")) {
                    fieldType = "String";
                }
                System.out.println("转换类型:" + fieldType);
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");

        dsc.setUsername("root");
        dsc.setPassword("00000");
        dsc.setUrl("jdbc:mysql://190.289.20.1:3306/***?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = mpGenerator.getPackageConfig();
        mpg.setPackageInfo(pc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();

        // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
        strategy.setTablePrefix(new String[]{""});// 此处可以修改为您的表前缀
        //下划线转驼峰命名法
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        //自动填充设置
        List<TableFill> tableFillList = new ArrayList<TableFill>();
        tableFillList.add(new TableFill("create_date", FieldFill.INSERT));//设置为插入时自动填充
        tableFillList.add(new TableFill("update_date", FieldFill.INSERT_UPDATE));//设置为更新时自动填充
        strategy.setTableFillList(tableFillList);
        strategy.setRestControllerStyle(true);
        String tables = mpGenerator.scanner("表名,以逗号隔开需要生成的表");
        if (tables.length() != 0) {
            if ((tables.charAt(tables.length() - 1)) == ',') {
                tables = tables.substring(0, tables.length() - 1);
            }
            String[] tabless = tables.split(",");

            strategy.setInclude(tabless); // 需要生成的表
        }
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
                Map<String,Object> map = new HashMap<>();
                this.setMap(map);
            }
        };

        // 如果模板引擎是 freemarker
        // String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";
        String entityP
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值