MyBatis Generator生成DAO——序列化

MyBatis Generator生成DAO 的时候,生成的类都是没有序列化的。

还以为要手工加入(開始是手工加入的),今天遇到分页的问题,才发现生成的时候能够加入插件。

既然分页能够有插件。序列化是不是也有呢。

果然SerializablePlugin,已经给我们提供好了。

 <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

立即高端大气了起来。每一个model对象都乖乖的带上了Serializable接口。

无奈仅仅有model对象是不够的,做分布式开发的话。Example对象也必需要序列化。

于是下载了SerializablePlugin的源代码。model能够有。Example肯定也能够有。不出所料稍作改动就加上了。

(直接用原来的源代码加入了自己的代码)

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.util.List;
import java.util.Properties;

/**
 * Created by tiantao on 15-7-1.
 */
public class SerializablePlugin extends PluginAdapter {

    private FullyQualifiedJavaType serializable;
    private FullyQualifiedJavaType gwtSerializable;
    private boolean addGWTInterface;
    private boolean suppressJavaInterface;

    public SerializablePlugin() {
        super();
        serializable = new FullyQualifiedJavaType("java.io.Serializable"); //$NON-NLS-1$
        gwtSerializable = new FullyQualifiedJavaType("com.google.gwt.user.client.rpc.IsSerializable"); //$NON-NLS-1$
    }

    public boolean validate(List<String> warnings) {
        // this plugin is always valid
        return true;
    }

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
        addGWTInterface = Boolean.valueOf(properties.getProperty("addGWTInterface")); //$NON-NLS-1$
        suppressJavaInterface = Boolean.valueOf(properties.getProperty("suppressJavaInterface")); //$NON-NLS-1$
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
                                                 IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    @Override
    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass,
                                                 IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    @Override
    public boolean modelRecordWithBLOBsClassGenerated(
            TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    /**
     * 加入给Example类序列化的方法
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,IntrospectedTable introspectedTable){
        makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    protected void makeSerializable(TopLevelClass topLevelClass,
                                    IntrospectedTable introspectedTable) {
        if (addGWTInterface) {
            topLevelClass.addImportedType(gwtSerializable);
            topLevelClass.addSuperInterface(gwtSerializable);
        }

        if (!suppressJavaInterface) {
            topLevelClass.addImportedType(serializable);
            topLevelClass.addSuperInterface(serializable);

            Field field = new Field();
            field.setFinal(true);
            field.setInitializationString("1L"); //$NON-NLS-1$
            field.setName("serialVersionUID"); //$NON-NLS-1$
            field.setStatic(true);
            field.setType(new FullyQualifiedJavaType("long")); //$NON-NLS-1$
            field.setVisibility(JavaVisibility.PRIVATE);
            context.getCommentGenerator().addFieldComment(field, introspectedTable);

            topLevelClass.addField(field);
        }
    }
}

哇咔咔,太好用了。Example都加上了。

只是问题还没有完,Example里还有内部类。假设不序列化还是会报错。

这次明显更刚才的套路不一样了。没有抱太大希望。

无意间发现了还有一个插件类,也是包里自带的。

发现了宝藏,这里居然有对内部类的操作。

import java.util.List;

import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.codegen.ibatis2.Ibatis2FormattingUtilities;

/**
 * This plugin demonstrates adding methods to the example class to enable
 * case-insensitive LIKE searches. It shows hows to construct new methods and
 * add them to an existing class.
 *
 * This plugin only adds methods for String fields mapped to a JDBC character
 * type (CHAR, VARCHAR, etc.)
 *
 * @author Jeff Butler
 *
 */
public class CaseInsensitiveLikePlugin extends PluginAdapter {

    /**
     *
     */
    public CaseInsensitiveLikePlugin() {
        super();
    }

    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
            IntrospectedTable introspectedTable) {

        InnerClass criteria = null;
        // first, find the Criteria inner class
        for (InnerClass innerClass : topLevelClass.getInnerClasses()) {
            if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$
                criteria = innerClass;
                break;
            }
        }

        if (criteria == null) {
            // can‘t find the inner class for some reason, bail out.
            return true;
        }

        for (IntrospectedColumn introspectedColumn : introspectedTable
                .getNonBLOBColumns()) {
            if (!introspectedColumn.isJdbcCharacterColumn()
                    || !introspectedColumn.isStringColumn()) {
                continue;
            }

            Method method = new Method();
            method.setVisibility(JavaVisibility.PUBLIC);
            method.addParameter(new Parameter(introspectedColumn
                    .getFullyQualifiedJavaType(), "value")); //$NON-NLS-1$

            StringBuilder sb = new StringBuilder();
            sb.append(introspectedColumn.getJavaProperty());
            sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
            sb.insert(0, "and"); //$NON-NLS-1$
            sb.append("LikeInsensitive"); //$NON-NLS-1$
            method.setName(sb.toString());
            method.setReturnType(FullyQualifiedJavaType.getCriteriaInstance());

            sb.setLength(0);
            sb.append("addCriterion(\"upper("); //$NON-NLS-1$
            sb.append(Ibatis2FormattingUtilities
                    .getAliasedActualColumnName(introspectedColumn));
            sb.append(") like\", value.toUpperCase(), \""); //$NON-NLS-1$
            sb.append(introspectedColumn.getJavaProperty());
            sb.append("\");"); //$NON-NLS-1$
            method.addBodyLine(sb.toString());
            method.addBodyLine("return (Criteria) this;"); //$NON-NLS-1$

            criteria.addMethod(method);
        }

        return true;
    }
}

把原来的方法再优化一下下。

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.util.List;
import java.util.Properties;

/**
 * Created by tiantao on 15-7-1.
 */
public class SerializablePlugin extends PluginAdapter {

    private FullyQualifiedJavaType serializable;
    private FullyQualifiedJavaType gwtSerializable;
    private boolean addGWTInterface;
    private boolean suppressJavaInterface;

    public SerializablePlugin() {
        super();
        serializable = new FullyQualifiedJavaType("java.io.Serializable"); //$NON-NLS-1$
        gwtSerializable = new FullyQualifiedJavaType("com.google.gwt.user.client.rpc.IsSerializable"); //$NON-NLS-1$
    }

    public boolean validate(List<String> warnings) {
        // this plugin is always valid
        return true;
    }

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
        addGWTInterface = Boolean.valueOf(properties.getProperty("addGWTInterface")); //$NON-NLS-1$
        suppressJavaInterface = Boolean.valueOf(properties.getProperty("suppressJavaInterface")); //$NON-NLS-1$
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
                                                 IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    @Override
    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass,
                                                 IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    @Override
    public boolean modelRecordWithBLOBsClassGenerated(
            TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass, introspectedTable);
        return true;
    }

    /**
     * 加入给Example类序列化的方法
     * @param topLevelClass
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,IntrospectedTable introspectedTable){
        makeSerializable(topLevelClass, introspectedTable);

        for (InnerClass innerClass : topLevelClass.getInnerClasses()) {
            if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$
                innerClass.addSuperInterface(serializable);
            }
            if ("Criteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$
                innerClass.addSuperInterface(serializable);
            }
            if ("Criterion".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$
                innerClass.addSuperInterface(serializable);
            }
        }

        return true;
    }

    protected void makeSerializable(TopLevelClass topLevelClass,
                                    IntrospectedTable introspectedTable) {
        if (addGWTInterface) {
            topLevelClass.addImportedType(gwtSerializable);
            topLevelClass.addSuperInterface(gwtSerializable);
        }

        if (!suppressJavaInterface) {
            topLevelClass.addImportedType(serializable);
            topLevelClass.addSuperInterface(serializable);

            Field field = new Field();
            field.setFinal(true);
            field.setInitializationString("1L"); //$NON-NLS-1$
            field.setName("serialVersionUID"); //$NON-NLS-1$
            field.setStatic(true);
            field.setType(new FullyQualifiedJavaType("long")); //$NON-NLS-1$
            field.setVisibility(JavaVisibility.PRIVATE);
            context.getCommentGenerator().addFieldComment(field, introspectedTable);

            topLevelClass.addField(field);
        }
    }
}

哇咔咔。成功了。

时间: 2024-08-08 09:40:41

MyBatis Generator生成DAO——序列化的相关文章

Mybatis入门实例(三)——使用MyBatis Generator生成DAO(转载http://qiuqiu0034.iteye.com/blog/1163026)

接上回 http://qiuqiu0034.iteye.com/blog/1162952 虽然MyBatis很方便,但是想要手写全部的mapper还是很累人的,好在MyBatis官方推出了自动化工具,可以根据数据库和定义好的配置直接生成DAO层及以下的全部代码,非常方便. 需要注意的是,虽然自动化工具需要一个配置文件,但是MyBatis的配置文件仍然不能少,自动化工具的配置文件用于对生成的代码的选项进行配置,MyBatis的配置文件才是运行时的主要配置文件. 这个工具叫做MyBatis_Gene

mybatis generator生成代码工具的使用

mybatis generator生成代码工具的使用, 附demo 使用Hibernate时, 可以很方便的生成model,dao,和映射配置文件.在mybatis里, 也有生成器, 即mybatis generator, 简称MBG. 下面为大家介绍一下MBG的使用. 下载mybatis-generator-core-1.3.1-bundle.zip之后, 解压得到mybatis-generator-core-1.3.1.jar, 即生成器的jar包, 将mybatis-3.0.6.jar和m

Maven下用MyBatis Generator生成文件

使用Maven命令用MyBatis Generator生成MyBatis的文件步骤如下: 1.在mop文件内添加plugin <build> <finalName>KenShrio</finalName> <defaultGoal>compile</defaultGoal> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <

mybatis generator生成连接mysql与sqlserver的区别

mybatis generator生成连接mysql与sqlserver所在的区别在于驱动和数据库URL不同 mybatis generator连接mysql的配置文件是: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.

MyBatis自动生成Dao层

MyBatis自动生成Dao层 MyBatis自动生成Dao层,从数据库的表映射到Java的数据层.包括 Mapper接口的定义,Mapper文件中的sql脚本以及接口中用到的对象 参考地址: http://mybatis.org/generator/running/runningWithMaven.html http://mybatis.org/generator/configreference/xmlconfig.html 新建Maven项目(我的是基于SpringBoot) 1.配置pom

去掉Mybatis Generator生成的一堆Example类

上篇讲了如何使用Mybatis Generator生成代码,但是再生成过程中,往往出现一大堆的Example类,而这些Example中的很多方法我们是不需要用到的,因此在生成之前我们可以添加如下代码: <table schema="general" tableName="tb_table_name" domainObjectName="EntityName" enableCountByExample="false" en

MyBatis---使用MyBatis Generator生成Dto、Dao、Mapping

由于MyBatis属于一种半自动的ORM框架,所以主要的工作将是书写Mapping映射文件,但是由于手写映射文件很容易出错,所以查资料发现有现成的工具可以自动生成底层模型类.Dao接口类甚至Mapping映射文件. 生成代码需要的文件和jar包: (上图文件下载地址:http://download.csdn.net/detail/u012909091/7206091) 其中有mybatis框架的jar包,数据库驱动程序jar包以及MyBatis生成器jar包.其中的generatorConfig

mybatis自动生成dao, model, mapper xml文件

用mybatis的时候,手写xml或model文件是一个力气活,所以可以用mybatis-gennerator插件自动生成mybatis所需要的dao.bean.mapper xml文件 (原文地址:http://blog.csdn.net/tolcf/article/details/50835165) 附件下载地址:http://files.cnblogs.com/files/cc-robot/generator.rar 把附件解压到本地,我放在d:\web\java目录下了 只需要修改下面x

mybatis generator生成带有分页的Mybatis代码

MyBatis开发,最让人开心的就是可以随意写SQL,这样有多好的性能的SQL都可以进行调优. 但是MyBatis的优点也是它的缺点,不论什么项目都需要编写SQL,令人头疼的要命,一般业务(例如单表操作)的简单查询.修改.删除.插入,都需要自己手工去编写SQL. 还好有第三方的软件给我解决这些事情,可以像使用Hibernate一样使用MyBatis,当需要进行特殊定制的再进行修改. 1.      本文档主要描述 1.表格: 2.视图:3.存储过程:4.自定义的MyBatis 1.1.