Mybatis generator 代码生成器添加自定义方法

代码生成器生成的接口查询的话,没有查询单条数据的,返回的是一个集合,然后去判空,再获取第一个数据,多写了不必要的步骤。所以直接如果能生成一个接口,直接返回一条数据就好了。废话不多说,增加根据id查询一条数据的接口。

有三个文件

public class CustomPlugin extends PluginAdapter {

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }
    
    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        AbstractXmlElementGenerator elementGenerator = new CustomAbstractXmlElementGenerator();
        elementGenerator.setContext(context);
        elementGenerator.setIntrospectedTable(introspectedTable);
        elementGenerator.addElements(document.getRootElement());
        return super.sqlMapDocumentGenerated(document, introspectedTable);
    }

    @Override
    public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {
        AbstractJavaMapperMethodGenerator methodGenerator = new CustomJavaMapperMethodGenerator();
        methodGenerator.setContext(context);
        methodGenerator.setIntrospectedTable(introspectedTable);
        methodGenerator.addInterfaceElements(interfaze);
        return super.clientGenerated(interfaze, introspectedTable);
    }
}
public class CustomMapperGenerator extends AbstractJavaMapperMethodGenerator {

    @Override
    public void addInterfaceElements(Interface interfaze) {
        
        addInterfaceFindById(interfaze);
    }
    
    // 根据主键查询数据
    private void addInterfaceFindById(Interface interfaze) {
        // 先创建import对象
        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
        // 添加Object的包
        importedTypes.add(FullyQualifiedJavaType.getObjectInstance());
        // 创建方法对象
        Method method = new Method("findById");
        // 设置该方法为public
        method.setVisibility(JavaVisibility.PUBLIC);
        // 设置返回类型是对象类型
        FullyQualifiedJavaType returnType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        // 方法对象设置返回类型对象
        method.setReturnType(returnType);
        // 设置方法名称为我们在IntrospectedTable类中初始化的 “selectByObject”
        method.setName("findById");
        //不要方法体
        method.setAbstract(true);
        // 设置参数类型是对象
        FullyQualifiedJavaType parameterType;
        
        //获取主键,默认一个
        List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
        parameterType = primaryKeyColumns.get(0).getFullyQualifiedJavaType();
        // import参数类型对象
        importedTypes.add(parameterType);
        // 为方法添加参数,变量名称
        method.addParameter(new Parameter(parameterType, primaryKeyColumns.get(0).getJavaProperty())); //$NON-NLS-1$
        //
        addMapperAnnotations(interfaze, method);
        context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
        if (context.getPlugins().clientSelectByPrimaryKeyMethodGenerated(method, interfaze, introspectedTable)) {
            interfaze.addImportedTypes(importedTypes);
            interfaze.addMethod(method);
        }
    }

    public void addMapperAnnotations(Interface interfaze, Method method) {
    }
}
public class CustomXmlGenerator extends AbstractXmlElementGenerator {

    @Override
    public void addElements(XmlElement parentElement) {
        
        StringBuilder sb = new StringBuilder();

        // 增加findById
        XmlElement findById = new XmlElement("select");
        findById.addAttribute(new Attribute("id", "findById"));
        findById.addAttribute(new Attribute("resultMap", "BaseResultMap"));
        List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
        findById.addAttribute(new Attribute("parameterType", primaryKeyColumns.get(0).getFullyQualifiedJavaType().getShortName()));
        XmlElement baseColumn = new XmlElement("include");

        //代码生成器生成的
        baseColumn.addAttribute(new Attribute("refid", "Base_Column_List"));
        findById.addElement(baseColumn);
        sb = new StringBuilder();
        sb.append(" from ");
        //表名
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
        sb.append(" where ");
        //主键字段   
        sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(primaryKeyColumns.get(0)));
        sb.append(" = ");
        //主键值   
        sb.append(MyBatis3FormattingUtilities.getParameterClause(primaryKeyColumns.get(0)));
        findById.addElement(new TextElement(sb.toString()));
        parentElement.addElement(findById);

    }

然后是在配置文件里面引入插件

<generatorConfiguration>
    <properties resource="generator11111.properties"/>
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 为模型生成序列化方法-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!-- 为生成的Java模型创建一个toString方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

        <!-- 这里引入插件-->
        <plugin type="com.macro.mall.mybaits.CustomPlugin"/>

        <!--生成mapper.xml时覆盖原文件-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
        <commentGenerator type="com.macro.mall.CommentGenerator">
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">
            <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题-->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <javaModelGenerator targetPackage="com.macro.mall.model" targetProject="mall-mbg/src/main/java"/>
        <sqlMapGenerator targetPackage="com.macro.mall.mapper" targetProject="mall-mbg/src/main/resources"/>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.mapper"
                             targetProject="mall-mbg/src/main/java"/>
        <!--生成全部表tableName设为%-->
        <table tableName="ums_member">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值