MyBatis Generator系列之五:直接通过Java调用MyBatis Generator

直接通过Java调用MyBatis Generator

准备数据表

两张表

oa_staff

CREATE TABLE `oa_staff` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL COMMENT '名字',
  `gender` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别:0->男,1->女',
  `birthday` date DEFAULT NULL,
  `address` varchar(80) DEFAULT NULL COMMENT '住址',
  `native_place` varchar(80) DEFAULT NULL COMMENT '籍贯',
  `hiredate` date DEFAULT NULL COMMENT '入职日期',
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='员工信息'

oa_user

CREATE TABLE `oa_user` (
  `id` bigint(20) unsigned NOT NULL,
  `username` varchar(16) NOT NULL COMMENT '用户名',
  `password` varchar(32) NOT NULL COMMENT '密码',
  `email` varchar(255) DEFAULT NULL COMMENT '邮箱',
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='oa系统用户'

maven项目

MyBatis Generator系列之五:直接通过Java调用MyBatis Generator_第1张图片

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.examplegroupId>
    <artifactId>mbg-javaartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <java.version>1.8java.version>
        <maven.compiler.source>${java.version}maven.compiler.source>
        <maven.compiler.target>${java.version}maven.compiler.target>
    properties>

    <dependencies>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.19version>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.mybatis.generatorgroupId>
            <artifactId>mybatis-generator-coreartifactId>
            <version>1.4.0version>
        dependency>
    dependencies>
project>

基于XML配置的Java生成

这个需要配合xml文件

package com.example;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 基于XML配置的Java生成
 */
public class XmlConfigGen {
    public static void main(String[] args) throws InvalidConfigurationException, IOException, XMLParserException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = false; // 是否覆盖
        File configFile = new File(Objects.requireNonNull(XmlConfigGen.class.getClassLoader().getResource("generatorConfig.xml")).getFile());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

generatorConfig.xml内容


<generatorConfiguration>
    <context id="simple" targetRuntime="MyBatis3Simple">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&autoReconnect=true&serverTimezone=PRC"
                        userId="root" password="123456"/>

        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>

        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"/>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>

        <table tableName="oa_staff">
            <generatedKey column="id" sqlStatement="MySql" />
        table>
        <table tableName="oa_user" />
    context>
generatorConfiguration>

基于Java配置的Java生成

纯粹在Java中配置

package com.example;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 基于Java配置的Java生成
 */
public class JavaConfigGen {
    public static void main(String[] args) throws InvalidConfigurationException, InterruptedException, SQLException, IOException {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = false; // 是否覆盖
        Configuration configuration = new Configuration();

        Context context = new Context(ModelType.CONDITIONAL);
        context.setId("simple");
        context.setTargetRuntime("MyBatis3Simple");

        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
        jdbcConnectionConfiguration.setDriverClass("com.mysql.cj.jdbc.Driver");
        jdbcConnectionConfiguration.setConnectionURL("jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&autoReconnect=true&serverTimezone=PRC");
        jdbcConnectionConfiguration.setUserId("root");
        jdbcConnectionConfiguration.setPassword("123456");
        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
        javaModelGeneratorConfiguration.setTargetPackage("com.example.model");
        javaModelGeneratorConfiguration.setTargetProject("src/main/java");
        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
        sqlMapGeneratorConfiguration.setTargetPackage("com.example.mapper");
        sqlMapGeneratorConfiguration.setTargetProject("src/main/resources");
        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
        javaClientGeneratorConfiguration.setTargetPackage("com.example.mapper");
        javaClientGeneratorConfiguration.setTargetProject("src/main/java");
        javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

        TableConfiguration t1 = new TableConfiguration(context);
        t1.setTableName("oa_staff");
        context.addTableConfiguration(t1);
        GeneratedKey generatedKey = new GeneratedKey("id", "MySql", false, "pre");
        t1.setGeneratedKey(generatedKey);
        TableConfiguration t2 = new TableConfiguration(context);
        t2.setTableName("oa_user");
        context.addTableConfiguration(t2);

        configuration.addContext(context);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

完整代码

https://gitee.com/tobybiao/MBG-examples

参考

Running MyBatis Generator With Java

你可能感兴趣的:(MyBatis,Generator,mybatis)