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

来源:互联网 发布:加强网络基础设施建设 编辑:程序博客网 时间:2024/06/04 17:59

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 中可以发现,默认是用DomainObjectNameMapper拼接到一起的,所以对于 mapperName 我们可以设置为{0}Dao,然后使用MessageFormat,以DomainObjectName作为一个参数去格式化 mapperName ,这样就能很简单的解决通配符情况下的问题。

mapperName 出现在org.mybatis.generator.api.IntrospectedTable类中的下面两个方法中:

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

平时我们在<context>中设置targetRuntime属性时,使用的是MyBatis3MyBatis3Simple,他们对应的两个类,都是继承自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$        }        setMyBatis3SqlProviderType(sb.toString());    }}

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

//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地址:

http://git.oschina.net/free/Mapper

上面两个类对应的包地址:

http://git.oschina.net/free/Mapper/tree/master/src/main/java/tk/mybatis/mapper/generator

2 0
原创粉丝点击