我可以动态生成mybaits Mapper吗?

时间:2016-05-25 04:16:47

标签: code-generation mybatis mybatis-generator

<javaClientGenerator type="XMLMAPPER" targetPackage="com.aaa.${module}.domain.mapper"  targetProject="src/main/resources">
  <property name="enableSubPackages" value="true" />
</javaClientGenerator>

var $ {module}可以是表配置中domainObjectName的值。

    <table schema="test" tableName="account" domainObjectName="Account" >
      <property name="useActualColumnNames" value="true"/>
    </table>

1 个答案:

答案 0 :(得分:0)

是的,但您很可能需要创建自定义javaClientGenerator。我不认为enableSubPackages属性的工作原理是这样的。在您的配置文件中,您将拥有:

<javaClientGenerator type="com.mydomain.MyJavaMapperGenerator" targetPackage="com.aaa.${module}.domain.mapper"  targetProject="src/main/java">
</javaClientGenerator>

然后您需要使用您自己的版本将现有JavaMapperGenerator子类化。类似于下面的选项1或2。 考虑到选项1的意外复杂性,选项2是我可能会选择的。

选项1 - 导致这种困难的是映射器类型存储在私有变量中,因此您必须创建一个全新的Interface对象,复制原始值:

public class MyJavaMapperGenerator extends JavaMapperGenerator {

    @Override
    public List<CompilationUnit> getCompilationUnits() {
        List<CompilationUnit> compliationUnits = super.getCompilationUnits();
        List<CompilationUnit> newCompliationUnits = new ArrayList<>();
        Interface mapper = (Interface)compliationUnits.get(0);
        String mapperType = mapper.getType().getFullyQualifiedName();
        Interface newMapper = new Interface(mapperType.replace("${module}",
            introspectedTable.getFullyQualifiedTable().getDomainObjectName().toLowerCase()));

        newMapper.getJavaDocLines().addAll(mapper.getJavaDocLines());
        newMapper.setVisibility(mapper.getVisibility());
        newMapper.setStatic(mapper.isStatic());
        newMapper.setFinal(mapper.isFinal());
        newMapper.getAnnotations().addAll(mapper.getAnnotations());

        newMapper.addImportedTypes(mapper.getImportedTypes());
        newMapper.getStaticImports().addAll(mapper.getStaticImports());
        newMapper.getSuperInterfaceTypes().addAll(mapper.getSuperInterfaceTypes());
        newMapper.getMethods().addAll(mapper.getMethods());
        newMapper.getFileCommentLines().addAll(mapper.getFileCommentLines());

        newCompliationUnits.add(newMapper);

        return newCompliationUnits;
    }

}

选项2 - 虽然它有点乱,我可能会从JavaMapperGenerator复制粘贴整个getCompilationsUnits()方法并修改设置类型的单行:

public class MyJavaMapperGenerator extends JavaMapperGenerator {

    @Override
    public List<CompilationUnit> getCompilationUnits() {
        ...
        //FullyQualifiedJavaType type = new FullyQualifiedJavaType(
        //        introspectedTable.getMyBatis3JavaMapperType());
        FullyQualifiedJavaType type = new FullyQualifiedJavaType(
                introspectedTable.getMyBatis3JavaMapperType().replace("${module}",
                introspectedTable.getFullyQualifiedTable().getDomainObjectName()
                                 .toLowerCase()));
        ...
    }

}