基于Java形式的Mybatis逆向工程(无配置文件,生成注释)

来源:互联网 发布:电脑无损播放软件 编辑:程序博客网 时间:2024/06/06 00:20

基于最新的Mybatis Generator版本

  <dependency>            <groupId>org.mybatis.generator</groupId>            <artifactId>mybatis-generator-core</artifactId>            <version>1.3.5</version>  </dependency>

使用Run Main方法的形式执行逆向工程,生成Java Model, Java Mapper,SQL Mapper。
同时对Model内属性添加注释,Mapper接口方法添加注释。

模块分为四个Java Class,

第一个是接口配置,替换原来的配置文件,同时固化可配置的选项,比配置文件形式简单明了。

package com.bob.config.root.mybatis.generate;import java.util.Arrays;import java.util.List;import org.mybatis.generator.api.JavaTypeResolver;/** * Mybatis逆向工程配置 * * @author  * @create 2017-09-30 9:19 */public interface MybatisGenerateConfigs {    //是否用逆向工程生成的Model,Dao,Mapper覆盖当前已存在的,若覆盖请做好备份工作    Boolean OVERRIDE_EXIST = false;    //指定要生成的Table    List<String> TABLES = Arrays.asList("emp_country", "emp_region");    //连接数据库驱动包 这里选择自己本地位置    //String CLASSPATH_ENTRY = "D:/profile/mysql-connector-java-5.1.44-bin.jar";    String CLASSPATH_ENTRY = "D:/profile/postgresql-42.1.4.jar";    //指定生成java文件的编码格式    String JAVA_FILEEN_CODING = "UTF-8";    //指定JDBC信息    /*String JDBC_DRIVERCLASS = "com.mysql.jdbc.Driver";    String JDBC_CONNECTIONURL = "jdbc:mysql://localhost:3306/project";    String JDBC_USER_NAME = "root";    String JDBC_PASSWORD = "lanboal";*/    String JDBC_DRIVERCLASS = "org.postgresql.Driver";    String JDBC_CONNECTIONURL = "jdbc:postgresql://rm-tatadminmap.pg.rdstest.tbsite.net:3432/campus_space";    String JDBC_USER_NAME = "adminmap";    String JDBC_PASSWORD = "adminmap";    //如果maven工程只是单独的一个工程,targetProject="src/main/resources"    //String DEFAULT_JAVA_TARGETPROJECT = "src/main/java";    //String DEFAULT_RESOURCES_TARGETPROJECT = "src/main/resources";    //若果maven工程是分模块的工程,即使时在当前模块下生产成Mybatis文件,也需要指定模块前缀,    // targetProject="指定模块的名称/路径",例如:targetProject="project-web/src/main/java"    String DEFAULT_JAVA_TARGETPROJECT = "project-web/src/main/java";    //java类和配置文件生成位置可以指向不同的项目    String DEFAULT_RESOURCES_TARGETPROJECT = "project-root/src/main/resources";    //指定Java Model生成位置    String JAVA_MODEL_TARGETPROJECT = DEFAULT_JAVA_TARGETPROJECT;    String JAVA_MODEL_TARGETPACKAGE = "com.bob.mvc.model";    //指定Java DAO接口生成位置    String JAVACLIENT_TARGETPROJECT = DEFAULT_JAVA_TARGETPROJECT;    String JAVACLIENT_TARGETPACKAGE = "com.bob.mvc.mapper";    //指定Mapper.xml生成位置    String SQLMAP_TARGETPROJECT = DEFAULT_RESOURCES_TARGETPROJECT;    String SQLMAP_TARGETPACKAGE = "com.bob.mvc.mapper";    /**     * 可设置自定义的类型解析器     * {@linkplain JavaTypeResolver}     */    String JAVA_TYPE_RESOLVER = null;}

第二个类是配置文件的Parser:

import java.util.ArrayList;import java.util.List;import org.mybatis.generator.config.CommentGeneratorConfiguration;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.Context;import org.mybatis.generator.config.JDBCConnectionConfiguration;import org.mybatis.generator.config.JavaClientGeneratorConfiguration;import org.mybatis.generator.config.JavaModelGeneratorConfiguration;import org.mybatis.generator.config.JavaTypeResolverConfiguration;import org.mybatis.generator.config.SqlMapGeneratorConfiguration;import org.mybatis.generator.config.TableConfiguration;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVA_TYPE_RESOLVER;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.CLASSPATH_ENTRY;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVACLIENT_TARGETPACKAGE;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVACLIENT_TARGETPROJECT;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVA_FILEEN_CODING;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVA_MODEL_TARGETPACKAGE;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVA_MODEL_TARGETPROJECT;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JDBC_CONNECTIONURL;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JDBC_DRIVERCLASS;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JDBC_PASSWORD;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JDBC_USER_NAME;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.SQLMAP_TARGETPACKAGE;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.SQLMAP_TARGETPROJECT;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.TABLES;/** * Mybatis逆向工程基于Java形式的配置解析器 * * @author  * @create 2017-09-30 9:17 */public class MybatisGeneratorConfiguration {    public Configuration configMybatisGenerator() {        Configuration configuration = new Configuration();        configuration.addClasspathEntry(CLASSPATH_ENTRY);        Context context = new Context(null);        context.setTargetRuntime("MyBatis3");        context.setId("bob");        context.addProperty("javaFileEncoding", JAVA_FILEEN_CODING);        //设置注解生成器        context.setCommentGeneratorConfiguration(generateCommentConfiguration());        //设置JDBC连接配置        context.setJdbcConnectionConfiguration(generateJDBCConnectionConfiguration());        //设置JDBC Type 与Java Type之间的映射解析器        context.setJavaTypeResolverConfiguration(generateJavaTypeResolverConfiguration());        //设置Java Model生成配置        context.setJavaModelGeneratorConfiguration(generateJavaModelGeneratorConfiguration());        //设置DAO层的生成配置        context.setSqlMapGeneratorConfiguration(generateSqlMapGeneratorConfiguration());        //设置Mapper.xml生成        context.setJavaClientGeneratorConfiguration(generateJavaClientGeneratorConfiguration());        //设置需要生成的Table及生成形式        for (TableConfiguration tableConfiguration : generateTableConfigurations(context)) {            context.addTableConfiguration(tableConfiguration);        }        configuration.addContext(context);        return configuration;    }    /**     * 配置注解生成器     *     * @return     */    private CommentGeneratorConfiguration generateCommentConfiguration() {        CommentGeneratorConfiguration configuration = new CommentGeneratorConfiguration();        configuration.setConfigurationType(GeneralCommentGenerator.class.getName());        //是否去除自动生成的注释 true:是 : false:否        configuration.addProperty("suppressAllComments", "false");        configuration.addProperty("addRemarkComments", "true");        return configuration;    }    /**     * 设置数据库连接的信息:驱动类、连接地址、用户名、密码     *     * @return     */    private JDBCConnectionConfiguration generateJDBCConnectionConfiguration() {        JDBCConnectionConfiguration configuration = new JDBCConnectionConfiguration();        configuration.setDriverClass(JDBC_DRIVERCLASS);        String jdbcSuffix = "?useUnicode=true&characterEncoding=UTF8&useSSL=false";        configuration.setConnectionURL(JDBC_CONNECTIONURL + jdbcSuffix);        configuration.setUserId(JDBC_USER_NAME);        configuration.setPassword(JDBC_PASSWORD);        return configuration;    }    /**     * 设置JDBC Type 与Java Type之间的映射解析器     *     * @return     */    private JavaTypeResolverConfiguration generateJavaTypeResolverConfiguration() {        JavaTypeResolverConfiguration configuration = new JavaTypeResolverConfiguration();        //可自定义类型映射解析器        configuration.setConfigurationType(JAVA_TYPE_RESOLVER);        //默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal        configuration.addProperty("forceBigDecimals", "true");        return configuration;    }    /**     * 配置Java Model生成     *     * @return     */    private JavaModelGeneratorConfiguration generateJavaModelGeneratorConfiguration() {        JavaModelGeneratorConfiguration configuration = new JavaModelGeneratorConfiguration();        configuration.setTargetProject(JAVA_MODEL_TARGETPROJECT);        configuration.setTargetPackage(JAVA_MODEL_TARGETPACKAGE);        //是否让schema作为包的后缀        configuration.addProperty("enableSubPackages", "false");        //从数据库返回的值被清理前后的空格        configuration.addProperty("trimStrings", "true");        return configuration;    }    /**     * 配置Mapper.xml生成     *     * @return     */    private SqlMapGeneratorConfiguration generateSqlMapGeneratorConfiguration() {        SqlMapGeneratorConfiguration configuration = new SqlMapGeneratorConfiguration();        configuration.setTargetProject(SQLMAP_TARGETPROJECT);        configuration.setTargetPackage(SQLMAP_TARGETPACKAGE);        //是否让schema作为包的后缀        configuration.addProperty("enableSubPackages", "false");        return configuration;    }    /**     * 设置DAO生成     *     * @return     */    private JavaClientGeneratorConfiguration generateJavaClientGeneratorConfiguration() {        JavaClientGeneratorConfiguration configuration = new JavaClientGeneratorConfiguration();        configuration.setConfigurationType("XMLMAPPER");        configuration.setTargetProject(JAVACLIENT_TARGETPROJECT);        configuration.setTargetPackage(JAVACLIENT_TARGETPACKAGE);        //是否让schema作为包的后缀        configuration.addProperty("enableSubPackages", "false");        return configuration;    }    private List<TableConfiguration> generateTableConfigurations(Context context) {        List<TableConfiguration> configurations = new ArrayList<TableConfiguration>();        for (String table : TABLES) {            TableConfiguration configuration = new TableConfiguration(context);            configuration.setTableName(table);            configuration.setSelectByExampleStatementEnabled(false);            configuration.setDeleteByExampleStatementEnabled(false);            configuration.setCountByExampleStatementEnabled(false);            configuration.setUpdateByExampleStatementEnabled(false);            configurations.add(configuration);        }        return configurations;    }}

第三个类是注释生成器,借鉴了网上一位同行写的详细的注释模板:

import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Properties;import org.mybatis.generator.api.CommentGenerator;import org.mybatis.generator.api.IntrospectedColumn;import org.mybatis.generator.api.IntrospectedTable;import org.mybatis.generator.api.dom.java.CompilationUnit;import org.mybatis.generator.api.dom.java.Field;import org.mybatis.generator.api.dom.java.InnerClass;import org.mybatis.generator.api.dom.java.InnerEnum;import org.mybatis.generator.api.dom.java.Method;import org.mybatis.generator.api.dom.java.Parameter;import org.mybatis.generator.api.dom.java.TopLevelClass;import org.mybatis.generator.api.dom.xml.TextElement;import org.mybatis.generator.api.dom.xml.XmlElement;import org.mybatis.generator.config.MergeConstants;import org.mybatis.generator.config.PropertyRegistry;import static org.mybatis.generator.internal.util.StringUtility.isTrue;/** * Mybatis逆向工程自定义注释生成器 * * @author  * @create 2017-09-30 9:22 */public class GeneralCommentGenerator implements CommentGenerator {    /**     * The properties.     */    private Properties properties;    /**     * The suppress all comments.     */    private boolean suppressAllComments;    /**     * The addition of table remark's comments.     * If suppressAllComments is true, this option is ignored     */    private boolean addRemarkComments;    private String currentDateStr;    private Map<String, String> userEnv;    /**     * Instantiates a new default comment generator.     */    public GeneralCommentGenerator() {        super();        properties = new Properties();        suppressAllComments = false;        addRemarkComments = false;        userEnv = System.getenv();        currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());    }    @Override    public void addConfigurationProperties(Properties properties) {        this.properties.putAll(properties);        suppressAllComments = isTrue(properties            .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));        addRemarkComments = isTrue(properties            .getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS));    }    @Override    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {        if (suppressAllComments) {            return;        }        field.addJavaDocLine("/**"); //$NON-NLS-1$        field.addJavaDocLine(" * " + introspectedColumn.getRemarks());        field.addJavaDocLine(" */"); //$NON-NLS-1$    }    @Override    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {        if (suppressAllComments) {            return;        }        field.addJavaDocLine("/**"); //$NON-NLS-1$        field.addJavaDocLine(" * " + introspectedTable.getFullyQualifiedTable());        field.addJavaDocLine(" */"); //$NON-NLS-1$    }    @Override    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {        if (suppressAllComments || !addRemarkComments) {            return;        }        topLevelClass.addJavaDocLine("/**"); //$NON-NLS-1$        topLevelClass.addJavaDocLine(" * 数据库表:" + introspectedTable.getFullyQualifiedTable());        topLevelClass.addJavaDocLine(" * ");        topLevelClass.addJavaDocLine(" * @author " + userEnv.get("USERNAME"));        topLevelClass.addJavaDocLine(" * @create " + currentDateStr);        topLevelClass.addJavaDocLine(" */"); //$NON-NLS-1$    }    @Override    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {        if (suppressAllComments) {            return;        }        innerClass.addJavaDocLine("/**"); //$NON-NLS-1$        innerClass.addJavaDocLine(" * 数据库表:" + introspectedTable.getFullyQualifiedTable());        innerClass.addJavaDocLine(" * ");        innerClass.addJavaDocLine(" * @author " + userEnv.get("USERNAME"));        innerClass.addJavaDocLine(" * @create " + currentDateStr);        innerClass.addJavaDocLine(" */"); //$NON-NLS-1$    }    @Override    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {        addClassComment(innerClass, introspectedTable);    }    @Override    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {    }    @Override    public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {        if (1 == 1) { //注销getter()方法的注释            return;        }        StringBuilder sb = new StringBuilder();        method.addJavaDocLine("/**"); //$NON-NLS-1$        //        method.addJavaDocLine(" * This method was generated by MyBatis Generator."); //$NON-NLS-1$        sb.append(" * 获取 "); //$NON-NLS-1$        sb.append(introspectedColumn.getRemarks()).append(" 字段:");        sb.append(introspectedTable.getFullyQualifiedTable());        sb.append('.');        sb.append(introspectedColumn.getActualColumnName());        method.addJavaDocLine(sb.toString());        method.addJavaDocLine(" *"); //$NON-NLS-1$        sb.setLength(0);        sb.append(" * @return "); //$NON-NLS-1$        sb.append(introspectedTable.getFullyQualifiedTable());        sb.append('.');        sb.append(introspectedColumn.getActualColumnName());        sb.append(", ");        sb.append(introspectedColumn.getRemarks());        method.addJavaDocLine(sb.toString());        method.addJavaDocLine(" */"); //$NON-NLS-1$    }    @Override    public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {        if (1 == 1) { //注销setter()方法的注释            return;        }        StringBuilder sb = new StringBuilder();        method.addJavaDocLine("/**"); //$NON-NLS-1$        //        method.addJavaDocLine(" * This method was generated by MyBatis Generator."); //$NON-NLS-1$        sb.append(" * 设置 ");  //$NON-NLS-1$        sb.append(introspectedColumn.getRemarks()).append(" 字段:");        sb.append(introspectedTable.getFullyQualifiedTable());        sb.append('.');        sb.append(introspectedColumn.getActualColumnName());        method.addJavaDocLine(sb.toString());        method.addJavaDocLine(" *"); //$NON-NLS-1$        Parameter parm = method.getParameters().get(0);        sb.setLength(0);        sb.append(" * @param "); //$NON-NLS-1$        sb.append(parm.getName());        sb.append(" the value for "); //$NON-NLS-1$        sb.append(introspectedTable.getFullyQualifiedTable());        sb.append('.');        sb.append(introspectedColumn.getActualColumnName());        sb.append(", ");        sb.append(introspectedColumn.getRemarks());        method.addJavaDocLine(sb.toString());        //        addJavadocTag(method, false);        method.addJavaDocLine(" */"); //$NON-NLS-1$    }    @Override    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {        StringBuilder sb = new StringBuilder();        method.addJavaDocLine("/**"); //$NON-NLS-1$        sb.append(" * ");        if (method.isConstructor()) {            sb.append(" 构造查询条件");        }        String method_name = method.getName();        if ("setOrderByClause".equals(method_name)) {            sb.append(" 设置排序字段");        } else if ("setDistinct".equals(method_name)) {            sb.append(" 设置过滤重复数据");        } else if ("getOredCriteria".equals(method_name)) {            sb.append(" 获取当前的查询条件实例");        } else if ("isDistinct".equals(method_name)) {            sb.append(" 是否过滤重复数据");        } else if ("getOrderByClause".equals(method_name)) {            sb.append(" 获取排序字段");        } else if ("createCriteria".equals(method_name)) {            sb.append(" 创建一个查询条件");        } else if ("createCriteriaInternal".equals(method_name)) {            sb.append(" 内部构建查询条件对象");        } else if ("clear".equals(method_name)) {            sb.append(" 清除查询条件");        } else if ("countByExample".equals(method_name)) {            sb.append(" 根据指定的条件获取数据库记录数");        } else if ("deleteByExample".equals(method_name)) {            sb.append(" 根据指定的条件删除数据库符合条件的记录");        } else if ("deleteByPrimaryKey".equals(method_name)) {            sb.append(" 根据主键删除数据库的记录");        } else if ("insert".equals(method_name)) {            sb.append(" 新写入数据库记录");        } else if ("insertSelective".equals(method_name)) {            sb.append(" 动态字段,写入数据库记录");        } else if ("selectByExample".equals(method_name)) {            sb.append(" 根据指定的条件查询符合条件的数据库记录");        } else if ("selectByPrimaryKey".equals(method_name)) {            sb.append(" 根据指定主键获取一条数据库记录");        } else if ("updateByExampleSelective".equals(method_name)) {            sb.append(" 动态根据指定的条件来更新符合条件的数据库记录");        } else if ("updateByExample".equals(method_name)) {            sb.append(" 根据指定的条件来更新符合条件的数据库记录");        } else if ("updateByPrimaryKeySelective".equals(method_name)) {            sb.append(" 动态字段,根据主键来更新符合条件的数据库记录");        } else if ("updateByPrimaryKey".equals(method_name)) {            sb.append(" 根据主键来更新符合条件的数据库记录");        }        sb.append(",");        sb.append(introspectedTable.getFullyQualifiedTable());        method.addJavaDocLine(sb.toString());        final List<Parameter> parameterList = method.getParameters();        if (!parameterList.isEmpty()) {            method.addJavaDocLine(" *");            if ("or".equals(method_name)) {                sb.append(" 增加或者的查询条件,用于构建或者查询");            }        } else {            if ("or".equals(method_name)) {                sb.append(" 创建一个新的或者查询条件");            }        }        String paramterName;        for (Parameter parameter : parameterList) {            sb.setLength(0);            sb.append(" * @param "); //$NON-NLS-1$            paramterName = parameter.getName();            sb.append(paramterName);            if ("orderByClause".equals(paramterName)) {                sb.append(" 排序字段"); //$NON-NLS-1$            } else if ("distinct".equals(paramterName)) {                sb.append(" 是否过滤重复数据");            } else if ("criteria".equals(paramterName)) {                sb.append(" 过滤条件实例");            }            method.addJavaDocLine(sb.toString());        }        if (method.getReturnType() != null) {            method.addJavaDocLine(" * @return");        }        method.addJavaDocLine(" */"); //$NON-NLS-1$    }    @Override    public void addJavaFileComment(CompilationUnit compilationUnit) {    }    @Override    public void addComment(XmlElement xmlElement) {        //当XmlElement添加了@mbg.generated后,下次再执行Mybatis Generate时不会重复生成此元素,但会将此元素还原成最初版本        xmlElement.addElement(new TextElement("<!--" + MergeConstants.NEW_ELEMENT_TAG + "-->")); //$NON-NLS-1$    }    @Override    public void addRootComment(XmlElement rootElement) {    int size = rootElement.getElements().size();        rootElement.addElement(size, new TextElement("<!--################################"            + " Mybatis逆向工程生成,请勿编辑! " + "################################-->"));    }}

最后一个类是逆向工程执行器,执行Main方法,同时做一些日志及执行前的校验工作:

package com.bob.config.root.mybatis.generate;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.internal.DefaultShellCallback;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;import org.springframework.util.Assert;import org.springframework.util.ClassUtils;import org.springframework.util.StringUtils;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.DEFAULT_JAVA_TARGETPROJECT;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.DEFAULT_RESOURCES_TARGETPROJECT;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVACLIENT_TARGETPACKAGE;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.JAVA_MODEL_TARGETPACKAGE;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.OVERRIDE_EXIST;import static com.bob.config.root.mybatis.generate.MybatisGenerateConfigs.SQLMAP_TARGETPACKAGE;/** * Mybatis逆向工程解析器 * 基于Mybatis Generator 1.3.5 Release * * @author wb-jjb318191 * @create 2017-09-28 17:08 */public class MybatisGenerator {    private static final Logger LOGGER = LoggerFactory.getLogger(MybatisGenerator.class);    /**     * Main函数,执行逆向工程     *     * @param args     * @throws Exception     */    public static void main(String[] args) throws Exception {        MybatisGenerator.generate();    }    /**     * 获取项目根路径     *     * @return     * @throws IOException     */    private String getRootPath() throws IOException {        String classPath = this.replaceDotByDelimiter(this.getClass().getName()) + ".class";        Resource resource = new ClassPathResource(classPath);        String path = resource.getFile().getAbsolutePath();        path = path.substring(0, path.indexOf("\\target"));        return path.substring(0, path.lastIndexOf("\\"));    }    /**     * 执行逆向工程     * 使用配置好的执行策略{@linkplain MybatisGenerateConfigs}     *     * @throws Exception     */    public static void generate() throws Exception {        new MybatisGenerator().generate(OVERRIDE_EXIST);        new MybatisGenerator().generate(true);    }    /**     * 执行逆向工程     *     * @param override 是否覆盖已存在的Model,Dao,Mapper     * @throws Exception     */    private void generate(boolean override) throws Exception {        if (!override) {            inspectGeneratedFilesExists();        }        Configuration config = new MybatisGeneratorConfiguration().configMybatisGenerator();        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, new DefaultShellCallback(true), new ArrayList<String>());        myBatisGenerator.generate(null);    }    /**     * 检测将通过逆向工程生成的Model,Dao,Mapper是否已存在     *     * @throws Exception     */    private void inspectGeneratedFilesExists() throws Exception {        LOGGER.info("非覆盖式执行Mybatis Generate,检查将要生成的文件是否已存在!");        List<String> classNames = convertTableToClassName(MybatisGenerateConfigs.TABLES);        String mapperPackage = replaceDotByDelimiter(SQLMAP_TARGETPACKAGE);        String remindMsg = "即将覆盖{}[{}],请确认做好备份后设置[{}]属性为true,执行后请还原为false";        String override = MybatisGenerateConfigs.class.getSimpleName() + "." + "OVERRIDE_EXIST";        boolean exists = false;        for (String clazzName : classNames) {            String modelName = JAVA_MODEL_TARGETPACKAGE + "." + clazzName;            if (exists = isClassExists(modelName)) {                LOGGER.warn(remindMsg, "Model Class", modelName, override);            }            String daoName = JAVACLIENT_TARGETPACKAGE + "." + clazzName + "Mapper";            if (exists = isClassExists(daoName)) {                LOGGER.warn(remindMsg, "DAO Class", daoName, override);            }            String mapperPath = mapperPackage + "/" + clazzName + "Mapper.xml";            if (exists = isMapperExists(mapperPath)) {                LOGGER.warn(remindMsg, "Mapper XML", mapperPath, override);            }        }        if (exists) {            throw new IllegalStateException("逆向工程生成的文件将会覆盖已存在文件,请备份好后设置覆盖式执行");        }    }    /**     * 依据驼峰原则格式化将表名转换为类名,当遇到下划线时去除下划线并对之后的一位字符大写     *     * @param tables     * @return     */    private List<String> convertTableToClassName(List<String> tables) {        List<String> classes = new ArrayList<String>();        for (String table : tables) {            classes.add(convertTableToClassName(table));        }        return classes;    }    /**     * 依据驼峰原则格式化将表名转换为类名,当遇到下划线时去除下划线并对之后的一位字符大写     *     * @param table     * @return     */    private String convertTableToClassName(String table) {        Assert.hasText(table, "表名不能为空");        StringBuilder sb = new StringBuilder();        sb.append(toUpperCase(table.charAt(0)));        for (int i = 1; i < table.length(); i++) {            sb.append('_' == table.charAt(i) ? toUpperCase(table.charAt(++i)) : table.charAt(i));        }        return sb.toString();    }    /**     * 将字符转换为大写     *     * @param ch     * @return     */    private char toUpperCase(char ch) {        return Character.toUpperCase(ch);    }    /**     * 使用'/'替换路径中的'.'     *     * @param path     * @return     */    private String replaceDotByDelimiter(String path) {        Assert.hasText(path, "替换路径不能为空");        return StringUtils.replace(path, ".", "/");    }    /**     * 项目是否是多模块项目     *     * @return     */    private boolean isMultiModuleProject() {        return !DEFAULT_JAVA_TARGETPROJECT.startsWith("src");    }    /**     * 验证类是否存在     *     * @param className     * @return     */    private boolean isClassExists(String className) throws IOException {        String javaSuffix = ".java";        Assert.hasText(className, "类名不能为空");        if(isMultiModuleProject()){            String absPath = this.getRootPath() + "/" + DEFAULT_JAVA_TARGETPROJECT + "/" +replaceDotByDelimiter(className) + javaSuffix;            return new FileSystemResource(absPath).exists();        }        return ClassUtils.isPresent(className, this.getClass().getClassLoader());    }    /**     * 验证文件是否存在     *     * @param mapperPath     * @return     */    public boolean isMapperExists(String mapperPath) throws IOException {        Assert.hasText(mapperPath, "Mapper路径不能为空");        if(isMultiModuleProject()){            String absPath = this.getRootPath() + "/" + DEFAULT_RESOURCES_TARGETPROJECT + "/" + mapperPath;            return new FileSystemResource(absPath).exists();        }        return new ClassPathResource(mapperPath).exists();    }}

以上就是基于Java形式的Mybatis Generator,代码没有太多优化,好用就行。
如果有什么问题和建议可以提。

原创粉丝点击