博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybatis-generator扩展教程系列 -- mapper xml文件增加自定义sql
阅读量:5786 次
发布时间:2019-06-18

本文共 22741 字,大约阅读时间需要 75 分钟。

     今天我教大家如何在mapper.xml文件里增加我们自定义的sql节点,还是老规矩沿用之前的项目用例,如有看不懂的同学可以翻看下上几篇的教程

1.打开IntrospectedTable.java找到enum InternalAttribute这个枚举定义增加一行我们的sql id ATTR_SELECT_BY_CONDITION_STATEMENT_ID

protected enum InternalAttribute {                /** The attr dao implementation type. */        ATTR_DAO_IMPLEMENTATION_TYPE,                /** The attr dao interface type. */        ATTR_DAO_INTERFACE_TYPE,                /** The attr primary key type. */        ATTR_PRIMARY_KEY_TYPE,                /** The attr base record type. */        ATTR_BASE_RECORD_TYPE,                /** The attr record with blobs type. */        ATTR_RECORD_WITH_BLOBS_TYPE,                /** The attr example type. */        ATTR_EXAMPLE_TYPE,                /** The ATT r_ ibati s2_ sq l_ ma p_ package. */        ATTR_IBATIS2_SQL_MAP_PACKAGE,                /** The ATT r_ ibati s2_ sq l_ ma p_ fil e_ name. */        ATTR_IBATIS2_SQL_MAP_FILE_NAME,                /** The ATT r_ ibati s2_ sq l_ ma p_ namespace. */        ATTR_IBATIS2_SQL_MAP_NAMESPACE,                /** The ATT r_ mybati s3_ xm l_ mappe r_ package. */        ATTR_MYBATIS3_XML_MAPPER_PACKAGE,                /** The ATT r_ mybati s3_ xm l_ mappe r_ fil e_ name. */        ATTR_MYBATIS3_XML_MAPPER_FILE_NAME,                /** also used as XML Mapper namespace if a Java mapper is generated. */        ATTR_MYBATIS3_JAVA_MAPPER_TYPE,                /** used as XML Mapper namespace if no client is generated. */        ATTR_MYBATIS3_FALLBACK_SQL_MAP_NAMESPACE,                /** The attr fully qualified table name at runtime. */        ATTR_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME,                /** The attr aliased fully qualified table name at runtime. */        ATTR_ALIASED_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME,                /** The attr count by example statement id. */        ATTR_COUNT_BY_EXAMPLE_STATEMENT_ID,                /** The attr delete by example statement id. */        ATTR_DELETE_BY_EXAMPLE_STATEMENT_ID,                /** The attr delete by primary key statement id. */        ATTR_DELETE_BY_PRIMARY_KEY_STATEMENT_ID,                /** The attr insert statement id. */        ATTR_INSERT_STATEMENT_ID,                /** The attr insert selective statement id. */        ATTR_INSERT_SELECTIVE_STATEMENT_ID,                /** The attr select all statement id. */        ATTR_SELECT_ALL_STATEMENT_ID,                /** The attr select by example statement id. */        ATTR_SELECT_BY_EXAMPLE_STATEMENT_ID,                /** The attr select by example with blobs statement id. */        ATTR_SELECT_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID,                /** The attr select by primary key statement id. */        ATTR_SELECT_BY_PRIMARY_KEY_STATEMENT_ID,                /** The attr update by example statement id. */        ATTR_UPDATE_BY_EXAMPLE_STATEMENT_ID,                /** The attr update by example selective statement id. */        ATTR_UPDATE_BY_EXAMPLE_SELECTIVE_STATEMENT_ID,                /** The attr update by example with blobs statement id. */        ATTR_UPDATE_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID,                /** The attr update by primary key statement id. */        ATTR_UPDATE_BY_PRIMARY_KEY_STATEMENT_ID,                /** The attr update by primary key selective statement id. */        ATTR_UPDATE_BY_PRIMARY_KEY_SELECTIVE_STATEMENT_ID,                /** The attr update by primary key with blobs statement id. */        ATTR_UPDATE_BY_PRIMARY_KEY_WITH_BLOBS_STATEMENT_ID,                /** The attr base result map id. */        ATTR_BASE_RESULT_MAP_ID,                /** The attr result map with blobs id. */        ATTR_RESULT_MAP_WITH_BLOBS_ID,                /** The attr example where clause id. */        ATTR_EXAMPLE_WHERE_CLAUSE_ID,                /** The attr base column list id. */        ATTR_BASE_COLUMN_LIST_ID,                /** The attr blob column list id. */        ATTR_BLOB_COLUMN_LIST_ID,                /** The ATT r_ mybati s3_ updat e_ b y_ exampl e_ wher e_ claus e_ id. */        ATTR_MYBATIS3_UPDATE_BY_EXAMPLE_WHERE_CLAUSE_ID,                /** The ATT r_ mybati s3_ sq l_ provide r_ type. */        ATTR_MYBATIS3_SQL_PROVIDER_TYPE,                ATTR_SELECT_BY_CONDITION_STATEMENT_ID // 通过条件查询SQL ID    }

2.IntrospectedTable.java增加sql id的set,get方法用于之后的读取操作

public void setSelectByConditionStatementId(String s) {        internalAttributes.put(InternalAttribute.ATTR_SELECT_BY_CONDITION_STATEMENT_ID, s);    }        public String getSelectByConditionStatementId() {        return internalAttributes                .get(InternalAttribute.ATTR_SELECT_BY_CONDITION_STATEMENT_ID);    }

3.新建一个xml sql生成的实现类SelectByConditionElementGenerator.java

package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;import org.mybatis.generator.api.IntrospectedColumn;import org.mybatis.generator.api.dom.xml.Attribute;import org.mybatis.generator.api.dom.xml.TextElement;import org.mybatis.generator.api.dom.xml.XmlElement;import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;/** *  * @author Jeff Butler *  */public class SelectByConditionElementGenerator extends        AbstractXmlElementGenerator {    public SelectByConditionElementGenerator() {        super();    }    @Override    public void addElements(XmlElement parentElement) {        XmlElement answer = new XmlElement("select"); //$NON-NLS-1$        answer.addAttribute(new Attribute(                "id", introspectedTable.getSelectByConditionStatementId())); //$NON-NLS-1$        if (introspectedTable.getRules().generateResultMapWithBLOBs()) {            answer.addAttribute(new Attribute("resultMap", //$NON-NLS-1$                    introspectedTable.getResultMapWithBLOBsId()));        } else {            answer.addAttribute(new Attribute("resultMap", //$NON-NLS-1$                    introspectedTable.getBaseResultMapId()));        }        String parameterType;        if (introspectedTable.getRules().generatePrimaryKeyClass()) {            parameterType = introspectedTable.getPrimaryKeyType();        } else {            // PK fields are in the base class. If more than on PK            // field, then they are coming in a map.            if (introspectedTable.getPrimaryKeyColumns().size() > 1) {                parameterType = "map"; //$NON-NLS-1$            } else {                parameterType = introspectedTable.getPrimaryKeyColumns().get(0)                        .getFullyQualifiedJavaType().toString();            }        }        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$                parameterType));        context.getCommentGenerator().addComment(answer);        StringBuilder sb = new StringBuilder();        sb.append("select "); //$NON-NLS-1$        if (stringHasValue(introspectedTable                .getSelectByPrimaryKeyQueryId())) {            sb.append('\'');            sb.append(introspectedTable.getSelectByPrimaryKeyQueryId());            sb.append("' as QUERYID,"); //$NON-NLS-1$        }        answer.addElement(new TextElement(sb.toString()));        answer.addElement(getBaseColumnListElement());        if (introspectedTable.hasBLOBColumns()) {            answer.addElement(new TextElement(",")); //$NON-NLS-1$            answer.addElement(getBlobColumnListElement());        }        sb.setLength(0);        sb.append("from "); //$NON-NLS-1$        sb.append(introspectedTable                .getAliasedFullyQualifiedTableNameAtRuntime());        answer.addElement(new TextElement(sb.toString()));        boolean and = false;        for (IntrospectedColumn introspectedColumn : introspectedTable                .getPrimaryKeyColumns()) {            sb.setLength(0);            if (and) {                sb.append("  and "); //$NON-NLS-1$            } else {                sb.append("where "); //$NON-NLS-1$                and = true;            }            sb.append(MyBatis3FormattingUtilities                    .getAliasedEscapedColumnName(introspectedColumn));            sb.append(" = "); //$NON-NLS-1$            sb.append(MyBatis3FormattingUtilities                    .getParameterClause(introspectedColumn));            answer.addElement(new TextElement(sb.toString()));        }        parentElement.addElement(answer);    }}

4.在XMLMapperGenerator.java中编写一个调用我们上面写的实现类方法

protected void addSelectByConditionElement(XmlElement parentElement) {        if (introspectedTable.getRules().generateSelectByPrimaryKey()) {            AbstractXmlElementGenerator elementGenerator = new SelectByConditionElementGenerator();            initializeAndExecuteGenerator(elementGenerator, parentElement);        }    }

5.在我们之前修改自定义xml sql id的地方增加调用,XMLMapperGenerator.java的getSqlMapElement()方法修改

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);                addResultMapWithoutBLOBsElement(answer);        addBaseColumnListElement(answer);        addInsertSelectiveElement(answer);        addUpdateByPrimaryKeySelectiveElement(answer);        addDeleteByPrimaryKeyElement(answer);        addSelectByConditionElement(answer); // 增加自定义SQL        return answer;    }
6.自定义sql的代码已经差不多这样了,根据之前的示例我们这次改造的地方其实不是很多,但是很实用;对于这个sql的拼写我只是简单的实现一个select all语句,更加复杂的你可以直接修改SelectByConditionElementGenerator.java实现类

下面我们可以看看执行成功后的结果,可以看到最下面多了一个select的语句

id, courseName, courseReq, teaId, teaName, stuId, stuName, stuPhone, textbookId, creator, lastModifier, countDate, countTime, countStu, sketchType, courseStyle, classType, process, courseStatus, pay, perPay, couponPay, originalPay, couponRule, beginDate, endDate, courseNum, hasNum, cancelNum, courseNumInput, orderNum, fav, vipLevel, cancelReason, createDate, lastModDate, formatter, status
insert into qfd_sketch
id,
courseName,
courseReq,
teaId,
teaName,
stuId,
stuName,
stuPhone,
textbookId,
creator,
lastModifier,
countDate,
countTime,
countStu,
sketchType,
courseStyle,
classType,
process,
courseStatus,
pay,
perPay,
couponPay,
originalPay,
couponRule,
beginDate,
endDate,
courseNum,
hasNum,
cancelNum,
courseNumInput,
orderNum,
fav,
vipLevel,
cancelReason,
createDate,
lastModDate,
formatter,
status,
#{id,jdbcType=BIGINT},
#{coursename,jdbcType=VARCHAR},
#{coursereq,jdbcType=VARCHAR},
#{teaid,jdbcType=VARCHAR},
#{teaname,jdbcType=VARCHAR},
#{stuid,jdbcType=VARCHAR},
#{stuname,jdbcType=VARCHAR},
#{stuphone,jdbcType=VARCHAR},
#{textbookid,jdbcType=BIGINT},
#{creator,jdbcType=VARCHAR},
#{lastmodifier,jdbcType=VARCHAR},
#{countdate,jdbcType=INTEGER},
#{counttime,jdbcType=INTEGER},
#{countstu,jdbcType=INTEGER},
#{sketchtype,jdbcType=INTEGER},
#{coursestyle,jdbcType=INTEGER},
#{classtype,jdbcType=INTEGER},
#{process,jdbcType=INTEGER},
#{coursestatus,jdbcType=INTEGER},
#{pay,jdbcType=VARCHAR},
#{perpay,jdbcType=VARCHAR},
#{couponpay,jdbcType=VARCHAR},
#{originalpay,jdbcType=VARCHAR},
#{couponrule,jdbcType=INTEGER},
#{begindate,jdbcType=BIGINT},
#{enddate,jdbcType=BIGINT},
#{coursenum,jdbcType=INTEGER},
#{hasnum,jdbcType=INTEGER},
#{cancelnum,jdbcType=INTEGER},
#{coursenuminput,jdbcType=INTEGER},
#{ordernum,jdbcType=INTEGER},
#{fav,jdbcType=BIGINT},
#{viplevel,jdbcType=INTEGER},
#{cancelreason,jdbcType=INTEGER},
#{createdate,jdbcType=BIGINT},
#{lastmoddate,jdbcType=BIGINT},
#{formatter,jdbcType=VARCHAR},
#{status,jdbcType=TINYINT},
update qfd_sketch
courseName = #{coursename,jdbcType=VARCHAR},
courseReq = #{coursereq,jdbcType=VARCHAR},
teaId = #{teaid,jdbcType=VARCHAR},
teaName = #{teaname,jdbcType=VARCHAR},
stuId = #{stuid,jdbcType=VARCHAR},
stuName = #{stuname,jdbcType=VARCHAR},
stuPhone = #{stuphone,jdbcType=VARCHAR},
textbookId = #{textbookid,jdbcType=BIGINT},
creator = #{creator,jdbcType=VARCHAR},
lastModifier = #{lastmodifier,jdbcType=VARCHAR},
countDate = #{countdate,jdbcType=INTEGER},
countTime = #{counttime,jdbcType=INTEGER},
countStu = #{countstu,jdbcType=INTEGER},
sketchType = #{sketchtype,jdbcType=INTEGER},
courseStyle = #{coursestyle,jdbcType=INTEGER},
classType = #{classtype,jdbcType=INTEGER},
process = #{process,jdbcType=INTEGER},
courseStatus = #{coursestatus,jdbcType=INTEGER},
pay = #{pay,jdbcType=VARCHAR},
perPay = #{perpay,jdbcType=VARCHAR},
couponPay = #{couponpay,jdbcType=VARCHAR},
originalPay = #{originalpay,jdbcType=VARCHAR},
couponRule = #{couponrule,jdbcType=INTEGER},
beginDate = #{begindate,jdbcType=BIGINT},
endDate = #{enddate,jdbcType=BIGINT},
courseNum = #{coursenum,jdbcType=INTEGER},
hasNum = #{hasnum,jdbcType=INTEGER},
cancelNum = #{cancelnum,jdbcType=INTEGER},
courseNumInput = #{coursenuminput,jdbcType=INTEGER},
orderNum = #{ordernum,jdbcType=INTEGER},
fav = #{fav,jdbcType=BIGINT},
vipLevel = #{viplevel,jdbcType=INTEGER},
cancelReason = #{cancelreason,jdbcType=INTEGER},
createDate = #{createdate,jdbcType=BIGINT},
lastModDate = #{lastmoddate,jdbcType=BIGINT},
formatter = #{formatter,jdbcType=VARCHAR},
status = #{status,jdbcType=TINYINT},
where id = #{id,jdbcType=BIGINT}
delete from qfd_sketch where id = #{id,jdbcType=BIGINT}

7.小结,我们自定义的sql作用范围很大,所以这个功能必须要改造的,sql增加了就要相应的增加dao类的方法名,可以参考之前的加成添加即可

转载地址:http://fltyx.baihongyu.com/

你可能感兴趣的文章
[SpringBoot] - 配置文件的多种形式及优先级
查看>>
chrome浏览器开发者工具之同步修改至本地
查看>>
debian7 + wheezy + chromium + flashplayer
查看>>
AOP
查看>>
进阶开发——文档,缓存,ip限速
查看>>
vue中子组件需调用父组件通过异步获取的数据
查看>>
uva 11468 - Substring(AC自己主动机+概率)
查看>>
Mysql 数据备份与恢复,用户创建,授权
查看>>
沉思录
查看>>
Angular.js中的$injector服务
查看>>
构建之法读书笔记01
查看>>
linux - lsof 命令最佳实践
查看>>
kafka性能测试
查看>>
现实世界的Windows Azure:h.e.t软件使用Windows Azure削减50%的成本
查看>>
深入.net框架
查看>>
聚合类新闻client产品功能点详情分析
查看>>
湘潭邀请赛——Alice and Bob
查看>>
js设置定时器
查看>>
数据库除运算
查看>>
LeetCode--112--路径总和
查看>>