天天看点

MyBatis Generator 1.3.4 扩展,可以设置 Mapper(Dao)后缀

MyBatis Generator 1.3.4 扩展

可以设置 Mapper(Dao)后缀

MyBatis Generator 简称 MBG,许多人在看 ​​MyBatis Generator 详解​​​ 的时候问过我能不能设置 Mapper 的后缀为 Dao,在当时的情况下是没法解决的。但是到了 1.3.4 版本,MBG 在​

​<table>​

​​元素上提供了一个 ​

​mapperName​

​ 的属性,可以设置生成的 Mapper 名字,使用方法如下:

<table tableName="sys_store" mapperName="StoreDao">
    <generatedKey column="id" sqlStatement="Mysql"/>
</table>      

本来默认情况下生成的 mapper 名字为​

​StoreMapper​

​​,通过上面设置后,就会生成 ​

​StroreDao​

​,对于一般情况的用法这就够了。

但是因为 ​

​tableName​

​​ 属性支持通配符 ​

​%​

​​,在这种情况下就不能使用​

​mapperName​

​属性设置了。为了解决这种情况,提供了一个插件可以用于通配符情况下的配置。

注意必须使用 MBG 1.3.4 或以上版本。

插件的思路很简单,在 MBG 中,使用 mapperName 的地方如下:

if (stringHasValue(tableConfiguration.getMapperName())) {
  sb.append(tableConfiguration.getMapperName());
} else {
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("Mapper"); //$NON-NLS-1$      

看 else 中可以发现,默认是用​

​DomainObjectName​

​​和​

​Mapper​

​​拼接到一起的,所以对于 ​

​mapperName​

​​ 我们可以设置为​

​{0}Dao​

​​,然后使用​

​MessageFormat​

​​,以​

​DomainObjectName​

​​作为一个参数去格式化 ​

​mapperName​

​ ,这样就能很简单的解决通配符情况下的问题。

mapperName 出现在​

​org.mybatis.generator.api.IntrospectedTable​

​类中的下面两个方法中:

//包含处理 Mapper 接口和 SqlProvider 的代码
protected void calculateJavaClientAttributes() {
    //...
}

//包含处理 Mapper.xml 的代码
protected String calculateMyBatis3XmlMapperFileName() {
}      

平时我们在​

​<context>​

​​中设置​

​targetRuntime​

​​属性时,使用的是​

​MyBatis3​

​​或​

​MyBatis3Simple​

​​,他们对应的两个类,都是继承自​

​IntrospectedTable​

​,所以我们修改的时候,要针对这两个继承的类去实现。

这里给出完整的代码:

//MyBatis3 的实现
public class TkMyBatis3Impl extends IntrospectedTableMyBatis3Impl
    @Override
    protected String calculateMyBatis3XmlMapperFileName() {
        StringBuilder sb = new StringBuilder();
        if (stringHasValue(tableConfiguration.getMapperName())) {
            String mapperName = tableConfiguration.getMapperName();
            int ind = mapperName.lastIndexOf('.');
            if (ind != -1) {
                mapperName = mapperName.substring(ind + 1);
            }
            //支持mapperName = "{0}Dao" 等用法
            sb.append(MessageFormat.format(mapperName, fullyQualifiedTable.getDomainObjectName()));
            sb.append(".xml"); //$NON-NLS-1$
        } else {
            sb.append(fullyQualifiedTable.getDomainObjectName());
            sb.append("Mapper.xml"); //$NON-NLS-1$
        }
        return sb.toString();
    }

    @Override
    protected void calculateJavaClientAttributes() {
        if (context.getJavaClientGeneratorConfiguration() == null) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(calculateJavaClientImplementationPackage());
        sb.append('.');
        sb.append(fullyQualifiedTable.getDomainObjectName());
        sb.append("DAOImpl"); //$NON-NLS-1$
        setDAOImplementationType(sb.toString());

        sb.setLength(0);
        sb.append(calculateJavaClientInterfacePackage());
        sb.append('.');
        sb.append(fullyQualifiedTable.getDomainObjectName());
        sb.append("DAO"); //$NON-NLS-1$
        setDAOInterfaceType(sb.toString());

        sb.setLength(0);
        sb.append(calculateJavaClientInterfacePackage());
        sb.append('.');
        if (stringHasValue(tableConfiguration.getMapperName())) {
            //支持mapperName = "{0}Dao" 等用法
            sb.append(MessageFormat.format(tableConfiguration.getMapperName(), fullyQualifiedTable.getDomainObjectName()));
        } else {
            sb.append(fullyQualifiedTable.getDomainObjectName());
            sb.append("Mapper"); //$NON-NLS-1$
        }
        setMyBatis3JavaMapperType(sb.toString());

        sb.setLength(0);
        sb.append(calculateJavaClientInterfacePackage());
        sb.append('.');
        if (stringHasValue(tableConfiguration.getSqlProviderName())) {
            //支持mapperName = "{0}SqlProvider" 等用法
            sb.append(MessageFormat.format(tableConfiguration.getSqlProviderName(), fullyQualifiedTable.getDomainObjectName()));
        } else {
            sb.append(fullyQualifiedTable.getDomainObjectName());
            sb.append("SqlProvider"); //$NON-NLS-1$      

另一个和上面代码一样,只是继承的类变了:

//MyBatis3Simple 的实现
public class TkMyBatis3Impl extends IntrospectedTableMyBatis3SimpleImpl
    //内容和上面的一样      

如何使用?

写个插件很容易,但是如何用对很多人来说都是一个大问题。

先说如何配置,再说如何运行。

配置

配置方式,只是修改​

​<context>​

​​的​

​targetRuntime​

​属性,如下:

<context id="Mysql" targetRuntime="tk.mybatis.mapper.generator.TkMyBatis3Impl">
</context>      

在​

​<table>​

​中配置的时候如下:

<!-- 注意:原有的用法不变,下面这么写可以省去部分名称 -->
<table tableName="sys_store" mapperName="{0}Dao">
    <generatedKey column="id" sqlStatement="Mysql"/>
</table>
<!-- 或者通配符情况 -->
<table tableName="sys%" mapperName="{0}Dao">
    <generatedKey column="id" sqlStatement="Mysql"/>
</table>      

运行

这里说明两种情况,其他的可以自行尝试。

在 IDE 中通过 Java 代码运行 MBG

如下代码:

List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(
        Surrogate.Generator.class.getResourceAsStream("/generator.xml"));
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);      

使用这种方式运行代码的时候,只需要保证上面两个实现的代码(或Jar)在当前运行的环境下(classpath)就可以使用。如果不在 classpath 下,就会因为找不到而报错。

在 CMD(命令行)执行

将代码打 jar 包,例如为 ​

​tk.mybatis.generator.jar​

命令行执行如下:

java -Dfile.encoding=UTF-8 -cp tk.mybatis.generator.jar;mybatis-generator-core-1.3.4.jar org.mybatis.generator.api.ShellRunner -configfile generatorConfig.xml -overwrite

这里通过 ​

​-cp​

​ 将需要用到的所有 jar 包放到当前的 classpath 下(分号隔开),这样在运行的时候就能找到相应的类。

另外 ​

​-Dfile.encoding=UTF-8​

​​ 可以保证生成代码的编码格式为​

​UTF-8​

​。

最后

上面两个类已经包含在 ​​通用Mapper​​ 中,通用Mapper地址: