课程咨询 :186 8716 1620      qq:2066486918

昆明Java培训 > 达内新闻 > 如何定制自己的mybatis生成
  • 如何定制自己的mybatis生成

    发布:昆明Java培训      来源:达内新闻      时间:2016-09-27

  • 昆明Java培训机构的老师给大家演示怎么来定制自己的mybatis生成

    MyBatis Generator原生提供的生成方式targetRuntime有几种,但都不符合项目需求或想自定义自己的方法。

    这里昆明Java培训机构的老师说下做法:

    1、继承IntrospectedTableMyBatis3Impl,重写自己要改写的方法

    InsoIntrospectedTable.java

    重写calculateXmlMapperGenerator使用自己的XMLMapperGenerator

    重写createJavaClientGenerator使用自己的JavaMapperGenerator

    昆明Java培训机构的老师做法比较粗暴,就是注释掉原来的逻辑,自己new自己的替代原来的。

    public class InsoIntrospectedTable extends IntrospectedTableMyBatis3Impl {

    protected void calculateXmlMapperGenerator(AbstractJavaClientGenerator javaClientGenerator,

    List<String> warnings,

    ProgressCallback progressCallback) {

    //       if (javaClientGenerator == null) {

    //           if (context.getSqlMapGeneratorConfiguration() != null) {

    //               xmlMapperGenerator = new XMLMapperGenerator();

    //           }

    //       } else {

    //           xmlMapperGenerator = javaClientGenerator.getMatchedXMLGenerator();

    //       }

    xmlMapperGenerator = new InsoXMLMapperGenerator();

    initializeAbstractGenerator(xmlMapperGenerator, warnings,

    progressCallback);

    }

    protected AbstractJavaClientGenerator createJavaClientGenerator() {

    if (context.getJavaClientGeneratorConfiguration() == null) {

    return null;

    }

    //       String type = context.getJavaClientGeneratorConfiguration()

    //               .getConfigurationType();

    AbstractJavaClientGenerator javaGenerator;

    //       if ("XMLMAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$

    //           javaGenerator = new JavaMapperGenerator();

    //       } else if ("MIXEDMAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$

    //           javaGenerator = new MixedClientGenerator();

    //       } else if ("ANNOTATEDMAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$

    //           javaGenerator = new AnnotatedClientGenerator();

    //       } else if ("MAPPER".equalsIgnoreCase(type)) { //$NON-NLS-1$

    //           javaGenerator = new JavaMapperGenerator();

    //       } else {

    //           javaGenerator = (AbstractJavaClientGenerator) ObjectFactory

    //                   .createInternalObject(type);

    //       }

    javaGenerator = new InsoJavaMapperGenerator();

    return javaGenerator;

    }

    }

    2、继承XMLMapperGenerator,重写自己要改写的方法

    InsoXMLMapperGenerator.java在getSqlMapElement方法中,可以添加或删除自己要的方法,这里我只添加了一个selectAll方法

    public class InsoXMLMapperGenerator extends XMLMapperGenerator {

    public InsoXMLMapperGenerator() {

    super();

    }

    protected XmlElement getSqlMapElement() {

    FullyQualifiedTable table = introspectedTable.getFullyQualifiedTable();

    progressCallback.startTask(getString(

    "Progress.12", table.toString())); //$NON-NLS-1$

    XmlElement answer = new XmlElement("mapper"); //$NON-NLS-1$

    String namespace = introspectedTable.getMyBatis3SqlMapNamespace();

    answer.addAttribute(new Attribute("namespace", //$NON-NLS-1$

    namespace));

    context.getCommentGenerator().addRootComment(answer);

    addResultMapWithoutBLOBsElement(answer);

    addResultMapWithBLOBsElement(answer);

    addExampleWhereClauseElement(answer);

    addMyBatis3UpdateByExampleWhereClauseElement(answer);

    addBaseColumnListElement(answer);

    addBlobColumnListElement(answer);

    addSelectByExampleWithBLOBsElement(answer);

    addSelectByExampleWithoutBLOBsElement(answer);

    addSelectByPrimaryKeyElement(answer);

    addDeleteByPrimaryKeyElement(answer);

    addDeleteByExampleElement(answer);

    addInsertElement(answer);

    addInsertSelectiveElement(answer);

    addCountByExampleElement(answer);

    addUpdateByExampleSelectiveElement(answer);

    addUpdateByExampleWithBLOBsElement(answer);

    addUpdateByExampleWithoutBLOBsElement(answer);

    addUpdateByPrimaryKeySelectiveElement(answer);

    addUpdateByPrimaryKeyWithBLOBsElement(answer);

    addUpdateByPrimaryKeyWithoutBLOBsElement(answer);

    //add select all

    addSimpleSelectAllElement(answer);

    return answer;

    }

    protected void addSimpleSelectAllElement(

    XmlElement parentElement) {

    if (introspectedTable.getRules()

    .generateSelectByPrimaryKey()) {

    AbstractXmlElementGenerator elementGenerator = new InsoSelectAllElementGenerator();

    initializeAndExecuteGenerator(elementGenerator, parentElement);

    }

    }

    }

    3、继承JavaMapperGenerator,重写自己要改写的方法

    InsoJavaMapperGenerator.java在getCompilationUnits方法中定制自己要的方法,这里我只添加了一个selectAll方法。

    注意:这里的项要与上面的XMLMapperGenerator一一对应,

    public class InsoJavaMapperGenerator extends JavaMapperGenerator {

    @Override

    public List<CompilationUnit> getCompilationUnits() {

    progressCallback.startTask(getString("Progress.17", //$NON-NLS-1$

    introspectedTable.getFullyQualifiedTable().toString()));

    CommentGenerator commentGenerator = context.getCommentGenerator();

    FullyQualifiedJavaType type = new FullyQualifiedJavaType(

    introspectedTable.getMyBatis3JavaMapperType());

    Interface interfaze = new Interface(type);

    interfaze.setVisibility(JavaVisibility.PUBLIC);

    commentGenerator.addJavaFileComment(interfaze);

    String rootInterface = introspectedTable

    .getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_INTERFACE);

    if (!stringHasValue(rootInterface)) {

    rootInterface = context.getJavaClientGeneratorConfiguration()

    .getProperty(PropertyRegistry.ANY_ROOT_INTERFACE);

    }

    if (stringHasValue(rootInterface)) {

    FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(

    rootInterface);

    interfaze.addSuperInterface(fqjt);

    interfaze.addImportedType(fqjt);

    }

    addCountByExampleMethod(interfaze);

    addDeleteByExampleMethod(interfaze);

    addDeleteByPrimaryKeyMethod(interfaze);

    addInsertMethod(interfaze);

    addInsertSelectiveMethod(interfaze);

    addSelectByExampleWithBLOBsMethod(interfaze);

    addSelectByExampleWithoutBLOBsMethod(interfaze);

    addSelectByPrimaryKeyMethod(interfaze);

    addUpdateByExampleSelectiveMethod(interfaze);

    addUpdateByExampleWithBLOBsMethod(interfaze);

    addUpdateByExampleWithoutBLOBsMethod(interfaze);

    addUpdateByPrimaryKeySelectiveMethod(interfaze);

    addUpdateByPrimaryKeyWithBLOBsMethod(interfaze);

    addUpdateByPrimaryKeyWithoutBLOBsMethod(interfaze);

    //增加selectAll

    addSelectAllMethod(interfaze);

    List<CompilationUnit> answer = ew ArrayList<CompilationUnit>();

    if (context.getPlugins().clientGenerated(interfaze, null,

    introspectedTable)) {

    answer.add(interfaze);

    }

    List<CompilationUnit> extraCompilationUnits = getExtraCompilationUnits();

    if (extraCompilationUnits != null) {

    answer.addAll(extraCompilationUnits);

    }

    return answer;

    }

    /**

    *增加eelectAll

    * @param interfaze

    */

    protected void addSelectAllMethod(Interface interfaze) {

    if (introspectedTable.getRules()

    .generateSelectByPrimaryKey()) {

    AbstractJavaMapperMethodGenerator methodGenerator = new SelectAllMethodGenerator();

    initializeAndExecuteGenerator(methodGenerator, interfaze);

    }

    }

    4、配置XML使用上面自定义targetRuntime

    inso-generator\src\main\resources\generatorConfig-sys.xml

    在targetRuntime中配置全路径类名

    在table节点,可以配置一些开关,是否生成某些方法,如下,我关掉生成ByExample的方法

    在table节点里,属性ignoreQualifiersAtRuntime,默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema,此配置,在Oracle下好用。

    <?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>

    <context id="default" targetRuntime="com.xxcomp.core.generator.codegen.InsoIntrospectedTable" defaultModelType="flat">

    <plugin type="com.xxcomp.core.generator.plugin.SerializablePlugin"/>

    <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

    <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>

    <plugin type="com.xxcomp.core.generator.plugin.MapperPlugin">

    <property ame="targetProject" value="../inso-sys-service/src/main/java"/>

    <property ame="targetPackage" value="com.xxcomp.dao.generator"/>

    <property ame="expandTargetPackage" value="com.xxcomp.dao.sys"/>

    </plugin>

    <commentGenerator>

    <property ame="suppressDate" value="true" />

    </commentGenerator>

    <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"

    connectionURL="jdbc:oracle:thin:@192.168.1.19:1521:EEMS"

    userId="TEST" password="TEST">

    </jdbcConnection>

    <javaTypeResolver>

    <property ame="forceBigDecimals" value="false"/>

    </javaTypeResolver>

    <javaModelGenerator targetPackage="com.xxcomp.model.generator" targetProject="../inso-sys-api/src/main/java">

    <property ame="constructorBased" value="false"/>

    <property ame="useActualColumnNames" value="true" />

    <property ame="enableSubPackages" value="false"/>

    <property ame="immutable" value="false"/>

    <property ame="trimStrings" value="true"/>

    <property ame="rootClass" value="com.xxcomp.core.base.BaseModel"/>

    </javaModelGenerator>

    <sqlMapGenerator targetPackage="mappers.generator" targetProject="../inso-sys-service/src/main/resources">

    <property ame="enableSubPackages" value="false"/>

    </sqlMapGenerator>

    <javaClientGenerator targetPackage="com.xxcomp.dao.generator" targetProject="../inso-sys-service/src/main/java" type="XMLMAPPER">

    <property ame="enableSubPackages" value=""/>

    <property ame="methodNameCalculator" value=""/>

    <property ame="rootInterface" value="com.xxcomp.core.base.BaseMapper"/>

    </javaClientGenerator>

    <table tableName="SYS_%" catalog="INSO" schema="INSO" enableCountByExample="false" enableUpdateByExample="false"   enableDeleteByExample="false" enableSelectByExample="false"   selectByExampleQueryId="false">

    <!--默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema;-->

    <property ame="ignoreQualifiersAtRuntime" value="true"/>

    </table>

    </context>

    </generatorConfiguration>

    5、pom文件参考

    项目原型是ibase4j(http://git.oschina.net/iBase4J/iBase4J),此pom仅供参考一下吧

    <?xml version="1.0"?>

    <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.0</modelVersion>

    <artifactId>inso-generator</artifactId>

    <name>inso-generator</name>

    <url>http://maven.apache.org</url>

    <packaging>jar</packaging>

    <parent>

    <groupId>com.xxcomp</groupId>

    <artifactId>inso</artifactId>

    <version>0.5.0</version>

    </parent>

    <!--使用不同配置文件生成不同项目的MyBatis文件-->

    <!-- install mybatis-generator:generate -DconfigurationFile=generatorConfig-scheduler.xml -->

    <!-- install mybatis-generator:generate -DconfigurationFile=generatorConfig-sys.xml -->

    <build>

    <finalName>${project.name}</finalName>

    <resources>

    <resource>

    <directory>src/main/java</directory>

    </resource>

    </resources>

    <pluginManagement>

    <plugins>

    <plugin>

    <groupId>org.apache.maven.plugins</groupId>

    <artifactId>maven-compiler-plugin</artifactId>

    <version>3.3</version>

    <configuration>

    <source>1.7</source>

    <target>1.7</target>

    <encoding>UTF-8</encoding>

    <testIncludes>

    <testInclude>none</testInclude>

    </testIncludes>

    </configuration>

    </plugin>

    <plugin>

    <groupId>org.apache.maven.plugins</groupId>

    <artifactId>maven-jdeps-plugin</artifactId>

    <version>3.0.0</version>

    <executions>

    <execution>

    <goals>

    <goal>jdkinternals</goal>

    <goal>test-jdkinternals</goal>

    </goals>

    </execution>

    </executions>

    </plugin>

    <plugin>

    <groupId>org.mybatis.generator</groupId>

    <artifactId>mybatis-generator-maven-plugin</artifactId>

    <version>1.3.2</version>

    <configuration>

    <verbose>true</verbose>

    <overwrite>true</overwrite>

    <configurationFile>src/main/resources/${configurationFile}</configurationFile>

    </configuration>

    <dependencies>

    <!--

    <dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>5.1.39</version>

    </dependency>

    -->

    <!--导入Oracle数据库链接jar包-->

    <dependency>

    <groupId>com.oracle</groupId>

    <artifactId>ojdbc6</artifactId>

    <version>11.2.0</version>

    </dependency>

    <dependency>

    <groupId>com.xxcomp</groupId>

    <artifactId>inso-generator</artifactId>

    <version>${project.version}</version>

    </dependency>

    </dependencies>

    <executions>

    <execution>

    <id>Generate MyBatis Artifacts</id>

    <goals>

    <goal>generate</goal>

    </goals>

    </execution>

    </executions>

    </plugin>

    </plugins>

    </pluginManagement>

    </build>

    </project>

    通过以上昆明Java培训机构的老师的改造,可以简单自定义组装一些原有的方法,生成自己需要的sqlMap,进一步还可以自己编写具体的方法实现,生成真正自定义的sql。

    推荐文章

上一篇:java程序员:springmvc添加mock json的支持

下一篇:Java培训机构: Spring集成Memcached缓存配置(二)

最新开班日期  |  更多

Java--零基础全日制班

Java--零基础全日制班

开班日期:12/29

Java--零基础业余班

Java--零基础业余班

开班日期:12/29

Java--周末提升班

Java--周末提升班

开班日期:12/29

Java--零基础周末班

Java--零基础周末班

开班日期:12/29

  • 网址:http://km .java.tedu.cn      地址:昆明市官渡区春城路62号证券大厦附楼6楼
  • 课程培训电话:186 8716 1620      qq:2066486918    全国服务监督电话:400-827-0010
  • 服务邮箱 ts@tedu.cn
  • 2001-2016 达内国际公司(TARENA INTERNATIONAL,INC.) 版权所有 京ICP证08000853号-56