mybatis反向生成sql,基本的增删改查

用到的几个文件

MyBatisGeneratorProxy.java

package com.timestech.wsgk.test.tools;

import static org.mybatis.generator.internal.util.ClassloaderUtility.getCustomClassloader;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.ProgressCallback;
import org.mybatis.generator.api.ShellCallback;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.ShellException;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.mybatis.generator.internal.NullProgressCallback;
import org.mybatis.generator.internal.ObjectFactory;
import org.mybatis.generator.internal.XmlFileMergerJaxp;

public class MyBatisGeneratorProxy {

    private Configuration configuration;

    private ShellCallback shellCallback;

    private List<GeneratedJavaFile> generatedJavaFiles;

    private List<GeneratedXmlFile> generatedXmlFiles;

    private List<String> warnings;

    private Set<String> projects;

    /**
     * Constructs a MyBatisGenerator object.
     *
     * @param configuration
     *            The configuration for this invocation
     * @param shellCallback
     *            an instance of a ShellCallback interface. You may specify
     *            <code>null</code> in which case the DefaultShellCallback will
     *            be used.
     * @param warnings
     *            Any warnings generated during execution will be added to this
     *            list. Warnings do not affect the running of the tool, but they
     *            may affect the results. A typical warning is an unsupported
     *            data type. In that case, the column will be ignored and
     *            generation will continue. You may specify <code>null</code> if
     *            you do not want warnings returned.
     * @throws InvalidConfigurationException
     *             if the specified configuration is invalid
     */
    public MyBatisGeneratorProxy(Configuration configuration, ShellCallback shellCallback,
            List<String> warnings) throws InvalidConfigurationException {
        super();
        if (configuration == null) {
            throw new IllegalArgumentException(getString("RuntimeError.2")); //$NON-NLS-1$
        } else {
            this.configuration = configuration;
        }

        if (shellCallback == null) {
            this.shellCallback = new DefaultShellCallback(false);
        } else {
            this.shellCallback = shellCallback;
        }

        if (warnings == null) {
            this.warnings = new ArrayList<String>();
        } else {
            this.warnings = warnings;
        }
        generatedJavaFiles = new ArrayList<GeneratedJavaFile>();
        generatedXmlFiles = new ArrayList<GeneratedXmlFile>();
        projects = new HashSet<String>();

        this.configuration.validate();
    }

    /**
     * This is the main method for generating code. This method is long running,
     * but progress can be provided and the method can be canceled through the
     * ProgressCallback interface. This version of the method runs all
     * configured contexts.
     *
     * @param callback
     *            an instance of the ProgressCallback interface, or
     *            <code>null</code> if you do not require progress information
     * @throws SQLException
     * @throws IOException
     * @throws InterruptedException
     *             if the method is canceled through the ProgressCallback
     */
    public void generate(ProgressCallback callback) throws SQLException,
            IOException, InterruptedException {
        generate(callback, null, null);
    }

    /**
     * This is the main method for generating code. This method is long running,
     * but progress can be provided and the method can be canceled through the
     * ProgressCallback interface.
     *
     * @param callback
     *            an instance of the ProgressCallback interface, or
     *            <code>null</code> if you do not require progress information
     * @param contextIds
     *            a set of Strings containing context ids to run. Only the
     *            contexts with an id specified in this list will be run. If the
     *            list is null or empty, than all contexts are run.
     * @throws InvalidConfigurationException
     * @throws SQLException
     * @throws IOException
     * @throws InterruptedException
     *             if the method is canceled through the ProgressCallback
     */
    public void generate(ProgressCallback callback, Set<String> contextIds)
            throws SQLException, IOException, InterruptedException {
        generate(callback, contextIds, null);
    }

    /**
     * This is the main method for generating code. This method is long running,
     * but progress can be provided and the method can be cancelled through the
     * ProgressCallback interface.
     *
     * @param callback
     *            an instance of the ProgressCallback interface, or
     *            <code>null</code> if you do not require progress information
     * @param contextIds
     *            a set of Strings containing context ids to run. Only the
     *            contexts with an id specified in this list will be run. If the
     *            list is null or empty, than all contexts are run.
     * @param fullyQualifiedTableNames
     *            a set of table names to generate. The elements of the set must
     *            be Strings that exactly match what‘s specified in the
     *            configuration. For example, if table name = "foo" and schema =
     *            "bar", then the fully qualified table name is "foo.bar". If
     *            the Set is null or empty, then all tables in the configuration
     *            will be used for code generation.
     * @throws InvalidConfigurationException
     * @throws SQLException
     * @throws IOException
     * @throws InterruptedException
     *             if the method is canceled through the ProgressCallback
     */
    public void generate(ProgressCallback callback, Set<String> contextIds,
            Set<String> fullyQualifiedTableNames) throws SQLException,
            IOException, InterruptedException {

        if (callback == null) {
            callback = new NullProgressCallback();
        }

        generatedJavaFiles.clear();
        generatedXmlFiles.clear();

        // calculate the contexts to run
        List<Context> contextsToRun;
        if (contextIds == null || contextIds.size() == 0) {
            contextsToRun = configuration.getContexts();
        } else {
            contextsToRun = new ArrayList<Context>();
            for (Context context : configuration.getContexts()) {
                if (contextIds.contains(context.getId())) {
                    contextsToRun.add(context);
                }
            }
        }

        // setup custom classloader if required
        if (configuration.getClassPathEntries().size() > 0) {
            ClassLoader classLoader = getCustomClassloader(configuration.getClassPathEntries());
            ObjectFactory.addExternalClassLoader(classLoader);
        }

        // now run the introspections...
        int totalSteps = 0;
        for (Context context : contextsToRun) {
            totalSteps += context.getIntrospectionSteps();
        }
        callback.introspectionStarted(totalSteps);

        for (Context context : contextsToRun) {
            context.introspectTables(callback, warnings,
                    fullyQualifiedTableNames);
        }

        // now run the generates
        totalSteps = 0;
        for (Context context : contextsToRun) {
            totalSteps += context.getGenerationSteps();
        }
        callback.generationStarted(totalSteps);

        for (Context context : contextsToRun) {
            context.generateFiles(callback, generatedJavaFiles,
                    generatedXmlFiles, warnings);
        }

        // now save the files
        callback.saveStarted(generatedXmlFiles.size()
                + generatedJavaFiles.size());

        for (GeneratedXmlFile gxf : generatedXmlFiles) {
            projects.add(gxf.getTargetProject());

            File targetFile;
            String source;
            try {
                File directory = shellCallback.getDirectory(gxf
                        .getTargetProject(), gxf.getTargetPackage());
                targetFile = new File(directory, gxf.getFileName());
                if (targetFile.exists()) {
                    if (gxf.isMergeable()) {
                        source = XmlFileMergerJaxp.getMergedSource(gxf,
                                targetFile);
                    } else if (shellCallback.isOverwriteEnabled()) {
                        source = gxf.getFormattedContent();
                        warnings.add(getString("Warning.11", //$NON-NLS-1$
                                targetFile.getAbsolutePath()));
                    } else {
                        source = gxf.getFormattedContent();
                        targetFile = getUniqueFileName(directory, gxf
                                .getFileName());
                        warnings.add(getString(
                                "Warning.2", targetFile.getAbsolutePath())); //$NON-NLS-1$
                    }
                } else {
                    source = gxf.getFormattedContent();
                }
            } catch (ShellException e) {
                warnings.add(e.getMessage());
                continue;
            }

            callback.checkCancel();
            callback.startTask(getString(
                    "Progress.15", targetFile.getName())); //$NON-NLS-1$
            writeFile(targetFile, source, "UTF-8"); //$NON-NLS-1$
        }

        for (GeneratedJavaFile gjf : generatedJavaFiles) {
            projects.add(gjf.getTargetProject());

            File targetFile;
            String source;
            String fileName;
            try {
                fileName = gjf.getFileName();
                File directory = shellCallback.getDirectory(gjf
                        .getTargetProject(), gjf.getTargetPackage());
                targetFile = new File(directory, fileName);
                if (targetFile.exists()) {
                    if (shellCallback.isMergeSupported()) {
                        source = shellCallback.mergeJavaFile(gjf
                                .getFormattedContent(), targetFile
                                .getAbsolutePath(),
                                MergeConstants.OLD_ELEMENT_TAGS,
                                gjf.getFileEncoding());
                    } else if (shellCallback.isOverwriteEnabled()) {
                        source = gjf.getFormattedContent();
                        warnings.add(getString("Warning.11", //$NON-NLS-1$
                                targetFile.getAbsolutePath()));
                    } else {
                        source = gjf.getFormattedContent();
                        targetFile = getUniqueFileName(directory, fileName);
                        warnings.add(getString(
                                "Warning.2", targetFile.getAbsolutePath())); //$NON-NLS-1$
                    }
                } else {
                    source = gjf.getFormattedContent();
                }
                if(!fileName.equals(gjf.getFileName())){
                    source = source.replace("interface " + gjf.getFileName().substring(0,gjf.getFileName().indexOf(".")),
                            "interface " + fileName.substring(0,fileName.indexOf(".")));
                }
                callback.checkCancel();
                callback.startTask(getString(
                        "Progress.15", targetFile.getName())); //$NON-NLS-1$
                writeFile(targetFile, source, gjf.getFileEncoding());
            } catch (ShellException e) {
                warnings.add(e.getMessage());
            }
        }

        for (String project : projects) {
            shellCallback.refreshProject(project);
        }

        callback.done();
    }

    /**
     * Writes, or overwrites, the contents of the specified file
     *
     * @param file
     * @param content
     */
    private void writeFile(File file, String content, String fileEncoding) throws IOException {
        FileOutputStream fos = new FileOutputStream(file, false);
        OutputStreamWriter osw;
        if (fileEncoding == null) {
            osw = new OutputStreamWriter(fos);
        } else {
            osw = new OutputStreamWriter(fos, fileEncoding);
        }

        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(content);
        bw.close();
    }

    private File getUniqueFileName(File directory, String fileName) {
        File answer = null;

        // try up to 1000 times to generate a unique file name
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < 1000; i++) {
            sb.setLength(0);
            sb.append(fileName);
            sb.append(‘.‘);
            sb.append(i);

            File testFile = new File(directory, sb.toString());
            if (!testFile.exists()) {
                answer = testFile;
                break;
            }
        }

        if (answer == null) {
            throw new RuntimeException(getString(
                    "RuntimeError.3", directory.getAbsolutePath())); //$NON-NLS-1$
        }

        return answer;
    }
}

MyBatisGeneratorTool.java---------run as 这个文件即可生成

package com.timestech.wsgk.test.tools;

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

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;

public class MyBatisGeneratorTool {

    public static void main(String[] args) throws UnsupportedEncodingException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        String genCfg = "/generator.xml"; //src/*/resources的一级目录下
        File configFile = new File(java.net.URLDecoder.decode(MyBatisGeneratorTool.class.getResource(genCfg).getFile(),"utf-8"));
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = null;
        try {
            config = cp.parseConfiguration(configFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGeneratorProxy myBatisGenerator = null;
        try {
            myBatisGenerator = new MyBatisGeneratorProxy(config, callback, warnings);
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        }
        try {
            System.out.println("begin generate......");
            myBatisGenerator.generate(null);
            System.out.println("end generate......");
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

generator.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="generatorConfig.properties"/>
    <classPathEntry location="${oracle.classPath}" />

    <context id="Mysql2Tables" targetRuntime="MyBatis3">
        <!-- 过滤掉注释 -->
        <commentGenerator>
              <property name="suppressAllComments" value="true" />
              <property name="suppressDate" value="true" />
        </commentGenerator>

        <!-- 数据链接 -->
        <jdbcConnection driverClass="${oracle.driverClass}"
            connectionURL="${oracle.connectionURL}"
            userId="${oracle.userId}"
            password="${oracle.password}">
        </jdbcConnection>

        <!-- 根据数据库字段长度自动匹配,默认为false:bigdecimal,long,int,short ,为true时始终使用bigdecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- domain类的生成 -->
        <javaModelGenerator targetPackage="${oracle.modelPackage}"
            targetProject="src/main/java">
            <!-- 是否允许在targetPackage目录下建子目录 -->
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- mapper文件生成 -->
        <sqlMapGenerator targetPackage="${oracle.sqlMapperPackage}"
            targetProject="src/main/java">
            <!-- 是否允许在targetPackage目录下建子目录 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- DAO生成 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="${oracle.daoMapperPackage}" targetProject="src/main/java">
            <!-- 是否允许在targetPackage目录下建子目录 -->
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="true" />
        </javaClientGenerator>

        <!-- 对应的数据库的哪张表,多个表的话就写多个table -->
        <table schema="bjlt" tableName="${oracle.tableName}" domainObjectName="${oracle.domainName}"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false">
            <!-- 指定id字段是Long类型,而不是BigDecimal类型 -->
            <columnOverride column="id" javaType="Long" />
        </table>

    </context>
</generatorConfiguration>

generatorConfig.properties-----生成文件的位置什么的在这里配置

#MYSQL数据库驱动
mysql.classPath=C\:/Users/Administrator/.m2/repository/mysql/mysql-connector-java/5.1.30/mysql-connector-java-5.1.30.jar
#targetProject=D\:/ylink/myeclipse/MBG/src
mysql.driverClass=com.mysql.jdbc.Driver
#链接数据库url
mysql.connectionURL=jdbc:mysql://192.168.0.121:3306/bjlt
#用户名
mysql.userId=root
#密码
mysql.password=root
#表名称
mysql.tableName=test
#domain名称
mysql.domainName=test
#domain类生成路径
mysql.modelPackage=com.timestech.wsgk.web.model
#mapper文件生成路径
mysql.sqlMapperPackage=com.timestech.wsgk.web.mapper
#DAO类生成路径
mysql.daoMapperPackage=com.timestech.wsgk.web.dao

#ORACLE数据库驱动
oracle.classPath=C\:/Users/Administrator/.m2/repository/com/oracle/ojdbc14/10.1.3/ojdbc14-10.1.3.jar
#targetProject=D\:/ylink/myeclipse/MBG/src
oracle.driverClass=oracle.jdbc.driver.OracleDriver
#链接数据库url
oracle.connectionURL=jdbc:oracle:thin:@192.168.0.121:1521:orcl
#用户名
oracle.userId=bjlt
#密码
oracle.password=bjlt
#表名称
oracle.tableName=BASESTATION
#domain名称
oracle.domainName=BASESTATION
#domain类生成路径
oracle.modelPackage=com.timestech.wsgk.web.model
#mapper文件生成路径
oracle.sqlMapperPackage=com.timestech.wsgk.web.mapper
#DAO类生成路径
oracle.daoMapperPackage=com.timestech.wsgk.web.dao
时间: 2024-10-17 07:08:12

mybatis反向生成sql,基本的增删改查的相关文章

通用DAO之MyBatis封装,封装通用的增删改查(二)

曾经发过一篇文章,大概写的就是阿海多么多么厉害,见到某位同事在Hibernate的基础上封装了一下,就以一己之力开发什么什么框架,最后写了个超大的一坨的事. 那么,后续篇来了.阿海不是自负之人,当之前的CRUD框架并没有达到理想的结果时,阿海转向了Mybatis封装.别问我为什么不是Hibernate.我本来就不喜欢Hibernate,即使在之前的一家公司一直被强制性的约束使用Hibernate时,也没有对Hibernate产生什么真正的好感,反而屡次发现了Hibernate的一些问题. 或许是

四种简单的sql语句(增删改查语句)

四种简单的sql语句(增删改查语句) 一.插入语句 insert into [table] ([column],[column],[column]) values(?,?,?) 二.删除语句 delete from [table] where column = ? 三.修改语句 update [table] set column = ? where column = ? 四.查询语句 1)查询单条记录的所有字段 select * from [table] where [column] = ? 2

mybatis 的 sql 映射文件增删改查的学习

在 sql 映射文件中配置增删改查的操作:     1.增: 在 sql 映射文件中添加 insert 标签,并且增加对应的 sql 语句.(在之前博文示例的基础上添加)在 对应的接口中添加 对应的方法,方法名与 sql 映射文件中 insert 标签中的 id 属性值一致. 注:可以看到,在测试方法 test03 中更新成功.但是在 openSession 对象需要手动提交事务.(sqlSessionFactory.openSession 方法的得到的 openSession 对象,使用 sq

通用DAO之MyBatis封装,封装通用的增删改查(三)

曾将发布过俩篇关于Mybatis封装的文章,当时曾曾承诺过当测试没有问题后阿海会整理一下然后将原代码发布出来. 那么今天正好朋友找我要一份那套mybatis封装的源码,我便整理了一份,想想这么长时间了并没有发现什么明显的bug,于是决定将它发出来. 喜欢的朋友可以在这里下载: http://aiyiupload.oss-cn-beijing.aliyuncs.com/blog/img/2016/06/28/15/6d69ad50-ab53-4f4f-b4e7-1fed010bfdb9.rar 关

SQL学习(二)SQL基础的增删改查

在测试时使用数据库时,用的比较多的就是增删改查SQL了. 一.增加(insert into ...values) 用于向表中插入新记录 1.不指定列(表示:依次插入所有列的值) insert into ticket values('2','测试') 2.指定列(表示:指定列插入数据) insert into ticket(name) values('测试') 二.删除(delete) 用于删除表中的行 1.删除所有行 delete from ticket 或:delete * from tick

Oracle+mybatis实现对数据的简单增删改查

第一步:--创建一个表空间:名字叫 mybatis,建在D盘下的date文件夹下: 第二步:创建用户,名字叫  lisi  ,密码为  :123456 第三步:给用户授权: 第四步:我们在    lisi  用户下创建一个emp表: 随便插入几个值: (这个表在网上有,可以扒下来) 第五步:(这里用的是eclipse)打开eclipse建立一个maven项目,在网上maven仓库中搜索mybatis导包 我们用3.4.6这个: 将这段代码粘在刚才在eclipse中建的项目的pom.xml中<必须

mybatis映射文件之基本的增删改查

借之前配置好的环境: 1.首先在Employee .java中加上有参的构造器和无参的构造器. 2.采用mapper中的class属性配置映射文件. <mappers> <mapper class="com.gong.mybatis.dao.EmployeeMapper" /> </mappers> 3.EmployeeMapper.java package com.gong.mybatis.dao; import com.gong.mybatis.

Spring mvc整合mybatis基于mysql数据库实现用户增删改查及其分页显示的完整入门实例【转】

Spring mvc整合mybatis例子, 基于mysql数据库实现对用户的增.删.改.查,及分页显示的完整例子. 查询显示用户 添加用户 更新用户 官方验证: 项目截图 必须修改applicationContext.xml中mysql的配置为本地的,否则启动失败. 另外jar包多一个ehcache.jar无关紧要,删除即可. 1. 使用阿里巴巴Druid连接池(高效.功能强大.可扩展性好的数据库连接池.监控数据库访问性能.支持Common-Logging.Log4j和JdkLog,监控数据库

Mybatis通过接口的方式实现增删改查

导入jar包 [mybatis] [oracle] 生成数据库 1.添加Mybatis的配置文件mybatis-config.xml 在src目录下创建一个mybatis-config.xml文件,如下图所示: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" &q