Java MyBatis (3)------Detailed custom Generator Plugin

Source: Internet
Author: User
Tags data structures generator modifier
1. Create base class

In a project, we often have to build a base class of entity classes with common methods to improve code reuse.
Suppose each table has field IDs and username, and each table requires a similar crud method (such as checking XX according to the primary key).

public class Basemodel implements Serializable {private String ID;
    private String name;
    Private Date CreateDate;
    Private Date modifydate;
    Private String creator;

    private String modifier;
    Public String GetId () {return id;
    public void SetId (String id) {this.id = ID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public Date Getcreatedate () {return createdate;
    The public void Setcreatedate (Date createdate) {this.createdate = CreateDate;
    Public Date Getmodifydate () {return modifydate;
    The public void Setmodifydate (Date modifydate) {this.modifydate = modifydate;
    Public String Getcreator () {return creator;
    } public void Setcreator (String creator) {this.creator = creator;
    Public String Getmodifier () {return modifier;

}    public void Setmodifier (String modifier) {this.modifier = modifier;
    } public interface Basedao<t extends basemodel> {list<t> selectall ();
    int Deletebyprimarykey (String ID);
    int Insert (T entity);
    int update (T entity, String ID);
T Selectbyprimarykey (String ID);
 }
2, writing Generatorconfig.xml
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis generator Configuration 1.0//en" "http: Mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <context id=" Basetables "Targetruntime=" MyBatis3 > <!--automatically generate ToString method--> <plugin type= "Org.mybatis.generator.plugin S.tostringplugin "/> <!--automatic generation of Equals method and Hashcode method--> <plugin type=" Org.mybatis.generator.plugi Ns. Equalshashcodeplugin "/> <!--customization method--> <plugin type=" Com.charlin.erp.common.base.plugin.Custom Ermapperplugin "> <property name=" targetproject "value=".
        /erp/src/main/java "/> <property name= targetpackage" value= "Com.charlin.erp.common.base.dao"/> </plugin> <!--custom method--> <plugin type= "Com.charlin.erp.common.base.plugin.SerializablePlu Gin "/> <Commentgenerator> <!--whether to remove automatically generated comments true: false: No--> <property name= "suppressallcom ments "value=" true "/> </commentGenerator> <!--database connection information: Driver class, connection address, user name, password--> <jdbc Connection driverclass= "Com.mysql.jdbc.Driver" connectionurl= "jdbc://mysql://localhost:3306/erp?ch Ararterencoding=utf8 "userid=" root password= "Sasa" ></jdbcConnection> <!--default F
        alse, resolves the jdbc decimal and NUMERIC types to integers, and resolves the jdbc decimal and NUMERIC types to Java.math.BigDecimal--> when True <javaTypeResolver> <property name= "Forcebigdecimals" value= "true" ></property> & Lt;/javatyperesolver> <!--targetproject: position to generate PO class--> <javamodelgenerator targetpackage= "com.c
            Harlin.erp.common.base.model "targetproject=". \src "> <!--enablesubpackages: Let schema be the suffix of the package--> <property Name= "Enablesubpackages" value= "true"/> <!--the space before and after the value returned from the database is cleaned--> <property name= "Trimstri NGS "value=" true "/> <!--horizontal--> <property name=" Rootclass "value="
        . Base.model.BaseModel "> </javaModelGenerator> <!--targetproject:mapper Map file build location--> <sqlmapgenerator targetpackage= "Com.charlin.erp.common.dao" targetproject= "\src" > <!--ENABLESUBPA Ckages: Allow schema as the suffix of the package--> <property name= "Enablesubpackages" value= "true"/> ator> <!--Targetpackage:mapper interface generated location--> <javaclientgenerator type= "Xmlmapper" targetpackage
            = "Com.charlin.erp.common.base.dao" targetproject= ". \src" > <!--enablesubpackages: Let schema be the suffix of the package--> <property name= "Enablesubpackages" value= "true"/> <property name= "Rootinterface" value= "C" Om.charlin.erp.common.baSe.dao.BaseDao "/> </javaClientGenerator> <!--Specify database table--> <table tablename=" items "></table> <table tablename=" Orders "></table> </context> </generatorconfiguratio N>
3, create Customermapperplugin
public class Customermapperplugin extends pluginadapter{private static final String Default_dao_super_class = "com.ch
    Arlin.erp.common.base.dao.BaseDao ";
    private static final String Default_expand_dao_super_class = "Com.charlin.erp.common.base.dao.BaseExpandDao";
    Private String Daotargetdir;
    Private String daotargetpackage;
    Private String Daosuperclass;
    Extend private String expanddaotargetpackage;
    Private String Expanddaosuperclass;

    Private Shellcallback shellcallback = null;
    Public Customermapperplugin () {this.shellcallback = new Defaultshellcallback (false); @Override public Boolean validate (list<string> warnings) {Daotargetdir = Properties.getproperty (
        "Targetproject");

        Boolean isdir = Stringhasvalue (Daotargetdir);
        Daotargetpackage = Properties.getproperty ("Targetpackage");

        Boolean ispackage = Stringhasvalue (daotargetpackage); Daosuperclass = Properties.getproperty ("DaosuperClass ");

        if (!stringhasvalue (daosuperclass)) Daosuperclass = Default_dao_super_class;
        Expanddaotargetpackage = Properties.getproperty ("Expanddaotargetpackage");
        Expanddaosuperclass = Properties.getproperty ("Expanddaosuperclass");

        if (!stringhasvalue (expanddaosuperclass)) Expanddaosuperclass = Default_expand_dao_super_class;
    return Isdir && ispackage;
        @Override public boolean sqlmapdocumentgenerated (document document, Introspectedtable introspectedtable) {
        XmlElement select = New XmlElement ("select");
        Select.addattribute (New Attribute ("id", "SelectAll"));
        Select.addattribute (New Attribute ("Resultmap", "Baseresultmap"));
        Select.addattribute (New Attribute ("ParameterType", Introspectedtable.getbaserecordtype ());

        Select.addelement (New TextElement ("SELECT * from" + introspectedtable.getfullyqualifiedtablenameatruntime ()));
XmlElement parentelement = Document.getrootelement ();        Parentelement.addelement (select);
    return super.sqlmapdocumentgenerated (document, introspectedtable); @Override public list<generatedjavafile> contextgenerateadditionaljavafiles (introspectedtable introspecte
        dtable) {Javaformatter javaformatter = Context.getjavaformatter ();
        list<generatedjavafile> mapperjavafiles = new arraylist<generatedjavafile> (); For (Generatedjavafile javaFile:introspectedTable.getGeneratedJavaFiles ()) {Compilationunit unit = Javafile.
            Getcompilationunit ();

            Fullyqualifiedjavatype Basemodeljavatype = Unit.gettype ();

            String shortname = Basemodeljavatype.getshortname ();

            Generatedjavafile mapperjavafile = null;
                    if (Shortname.endswith ("Mapper")) {//Extended Mapper if (Stringhasvalue (expanddaotargetpackage)) { Interface mapperinterface = new Interface (Expanddaotargetpackage + "." + Shortname.replace ("MappeR "," Expandmapper "));
                    Mapperinterface.setvisibility (Javavisibility.public);
                    Mapperinterface.addjavadocline ("/**");
                    Mapperinterface.addjavadocline ("*" + ShortName + "extended");

                    Mapperinterface.addjavadocline ("* *");
                    Fullyqualifiedjavatype Daosupertype = new Fullyqualifiedjavatype (expanddaosuperclass);
                    Mapperinterface.addimportedtype (Daosupertype);

                    Mapperinterface.addsuperinterface (Daosupertype);
                    Mapperjavafile = new Generatedjavafile (Mapperinterface, Daotargetdir, Javaformatter);
                        try {File Mapperdir = shellcallback.getdirectory (Daotargetdir, daotargetpackage);
                        File Mapperfile = new file (Mapperdir, Mapperjavafile. GetFileName ());
                            if (!mapperfile.exists ()) {//mapperfile.mkdirs (); MappeRjavafiles.add (Mapperjavafile);
                    } catch (Exception e) {e.printstacktrace ();  }}else if (!shortname.endswith ("Example")) {Interface mapperinterface = new
                Interface (Daotargetpackage + "." + ShortName + "Mapper");
                Mapperinterface.setvisibility (Javavisibility.public);
                Mapperinterface.addjavadocline ("/**");
                Mapperinterface.addjavadocline ("* generated automatically by the MyBatis Generator tool, please do not modify manually");

                Mapperinterface.addjavadocline ("* *");
                Fullyqualifiedjavatype Daosupertype = new Fullyqualifiedjavatype (daosuperclass);
                Add generics support Daosupertype.addtypeargument (Basemodeljavatype);
                Mapperinterface.addimportedtype (Basemodeljavatype);
                Mapperinterface.addimportedtype (Daosupertype); Mapperinterface.addsuperinterface (Daosupertype);

                Mapperjavafile = new Generatedjavafile (Mapperinterface, Daotargetdir, Javaformatter);
            Mapperjavafiles.add (Mapperjavafile);
    } return mapperjavafiles; }
}
4, Operation
public class Testgeneratorrun {

    @Test public
    void Test () throws exception{

    } public

    static void main ( String[] args) throws Exception {
        file configfile  = new File ("e:\\git\\erp\\common\\src\\main\\java\\com\\ Charlin\\erp\\common\\base\\generator\\generatorconfig.xml ");
        list<string> warnings = new arraylist<string> ();
        Boolean overwrite = true;
        Configurationparser cp = new Configurationparser (warnings);
        String FilePath = MyBatisGeneratorRun.class.getClassLoader (). GetResource (""). GetPath () + "Generatorconfig.xml";
        InputStream InputStream = new FileInputStream (configfile);
        Configuration config = cp.parseconfiguration (inputstream);
        Defaultshellcallback DSC = new Defaultshellcallback (overwrite);
        Mybatisgenerator mybatisgenerator = new Mybatisgenerator (config, DSC, warnings);
        Mybatisgenerator.generate (null);
    }

————————————————————————————————————————————————— – Java Architect Project Combat, high concurrency cluster distributed, large data high availability video tutorials, total 760G

Download Address:

https://item.taobao.com/item.htm?id=555888526201

01. High-level architect 42 Phases
02.Java Advanced System Training Architecture Course 148 hours
03.Java Senior Internet Architect Course
04.Java Internet Architecture Netty, Nio, Mina, etc.-Video tutorials
05.Java Advanced Architecture Design 2016 finishing-video tutorials
06. Architect Foundation, advanced film
07.Java Architect Required Linux Operation series courses
08.Java Advanced System Training Architecture Course 116 hours
+
Hadoop series tutorials, Java design patterns and data structures, Spring Cloud Micro service, Springboot Primer

—————————————————————————————————————————————————–

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.