이전 기사 Mybatis Reverse Engineering의 사용은 주로 Mybatis-Generator-Core-1.3.2.jar의 사용에 대해 이야기합니다. 이 기사에서 소개하고 싶은 것은 사용자 정의 템플릿 생성을 달성하기 위해 JAR 패키지 코드를 수정하는 것입니다.
1. 여기에서 우리는 mybatis-generator-core-1.3.2.jar project의 소스 코드를 다운로드 할 수 있습니다.
http://maven.outofmemory.cn/org.mybatis.generator/mybatis-generator-core/1.3.2/
2. Eclipse에서 기존 Maven 프로젝트를 가져 오십시오. 파일-> 가져 오기
프로젝트의 소스 코드 위치를 선택하고 마감을 클릭하여 가져 오기를 완료하십시오.
프로젝트 디렉토리 구조는 거의 이와 같습니다.
3. 아래에서는 매핑 및 XML 형식을 반전시켜 생성합니다.
4. 수정 시작, 먼저 각 디렉토리를 설명하십시오
하단의 TSE 패키지는 내 맞춤형 패키지이며, 이는 주요 클래스이며 생성 된 코드가 예상 표준을 충족하는지 여부를 테스트합니다.
이 패키지는 외국인에 의해 작성되었으므로 생성 된 코드 스타일은 우리와 거의 같지 않습니다. 코드 형식을 수정하려면 파인애플 코끼리에있는 기사를 읽는 것이 좋습니다. 여기에서 코드 형식에 대해서는 이야기하지 않습니다.
http://www.blogjava.net/bolo/archive/2015/03/20/423683.html
먼저, 먼저 리버스 프로젝트에서 생성 할 인터페이스 파일의 매핑 코드를 수정합니다. 기본적으로 추가, 삭제, 수정 및 검색이 있습니다. 업데이트 할 수정 방법 중 하나에 대해 이야기합시다.
예를 들어, 생성 된 매핑 void 업데이트 (map <string, object> datamap)에서 그러한 메소드를 원합니다.
org.mybatis.generator.codegen.mybatis3.javamapper.elements 패키지에서 org.mybatis.generator.codegen.javamapper.elements 패키지에서 updateByprimarykey를 변경하십시오.
/** Copyright 2009 Apache Software Foundation ** Apache 라이센스, 버전 2.0 ( "라이센스")에 따라 라이센스가 부여 된 경우 라이센스를 준수하는 것 외에이 파일을 사용할 수 없습니다. 기본,* 명시 적 또는 묵시적 보증 또는 조건이없는 경우.* 라이센스에 따른 특정 언어 거버넌스 권한 및* 제한에 대한 라이센스를 참조하십시오.*/Package org.mybatis.generator.codegen.mybatis3.javamapper.elements; import java.util.set; import java.util.treeyset; org.mybatis.generator.api.dom.java.lyderqualifiedjavatype; import org.mybatis.generator.api.dom.java.interface; import org.mybatis.generator.api.dom.java.javavisibility; import org.mybatis.generator.api.dom.java.java.method; org.mybatis.generator.api.dom.java.java.parameter;/**** @author jeff butler**/public class updatebyprimkeywithoutblobsmethodgenerator extendsabstractjavamapperMethodgenerator {public updateBlobsmethodgenerator {public update -primarykeywithoutblobsmethodgenerator ()}}} @ebonstridepublic void addInterfaceElements (Interface Interface) {set <fullicqualifiedjavatype> importedTypes = new treeset <ultequalifiedjavatype parametertype = new QualthQualifiedJavatype (introscedTable.getBasereCordType ()); new method.ad); Method (); // 메소드 수정 자 publiver.setvisability (javavisability.public); // 반환 값을 설정합니다. 여기서는 여기에서 사용자 정의 void를 사용합니다. getVoidinstance getVoidInstance () // 완전 값 값을 사용자 정의 할 수 있다면, 당신이 완전히 다시 Qualifice (returedjode)를 추가 할 수 있습니다. 생성자 메소드에서 입력하십시오 .SetReTurnType (FullicqualifiedJavatype.getVoidinstance ()); // 메소드 이름을 설정하면 이동할 수 있습니다. // $ non-nls-1 $ fullicqualifiedjavatype maptype = fullicqualifiedjavatype.getMymapInstance (); // 메소드의 매개 변수는 맵 유형 매개 변수의 Datemap 매개 변수 = 새 매개 변수 (mapType, "datamap")입니다. 방법 .addparameter (매개 변수); context.getCommentGenerator (). AddGeneralMethodcomment (메소드, introscedTable); addMapperAntations (Interfaze, Method); if (context.getPlugins (). ClientUpDateByPrimaryKeyWithOutBloBsMethodGenerated (Method, Interfaze, IntroctedTable)) {Interfaze.AdDimportedTypes (importedTypes); interfaze.addMethod (method);}} public void interfacenotations (interface interface) (interface) 주석에 따라 수정할 수 있습니다.
다음으로, 해당 XML에서 코드를 수정하십시오. 마찬가지로 여기에서는 업데이트 방법 만 소개합니다. 나는 그것을 읽은 후에는 다른 방법을 혼자서 수정할 수 있다고 생각합니다.
org.mybatis.generator.codegen.mybatis3.xmlmapper.elements 패키지에서 org.mybatis.generator.codegen.mybatis3.xmlmapper.elements 패키지 아래에서 updateByprimaryKey를 변경하십시오.
/** Copyright 2009 Apache Software Foundation ** Apache 라이센스, 버전 2.0 ( "라이센스")에 따라 라이센스가 부여 된 경우 라이센스를 준수하는 것 외에이 파일을 사용할 수 없습니다. 기본,* 명시 적 또는 묵시적 보증 또는 조건이없는 경우.* 라이센스에 따른 특정 언어 거버넌스 권한 및* 제한 사항에 대한 라이센스를 참조하십시오.*/Package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements; import java.util.iterator; import java.util.list; import java.util.list; org.mybatis.generator.api.introscedcolumn; import org.mybatis.generator.api.dom.outpututilities; import org.mybatis.generator.api.dom.xml.attribute; import org.mybatis.generator.api.dom.xml.xxtelement; 수입 org.mybatis.generator.api.dom.xml.XmlElement;import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;/*** * @author Jeff Butler* */public class UpdateByPrimaryKeyWithoutBLOBsElementGenerator extendsAbstractXmlElementGenerator {//private boolean issimple; issimple; public updateBodeMarywithoutBloBSelementGenerator (boolean issimple) {super (); // this.issimple = issimple;}@atrederPublic void addElements (xmlelement areSelement) {// 업데이트 태그 (방법의 외부 계층) XMLELENT 답변 = 새로운 XMLLEMENT ( "update"); // $ non-nls-1 $ // 업데이트 태그 답변의 엉덩이 .addattribute (new Attribute ( "id", introscedTable.getUpdateByPrimaryKeyStatidId ())); //$non-nls-1$ answer.addattribute(new attribute ( "parametertype", // $ non-nls-1 $ "map")); // 컨텍스트에 태그를 추가합니다. getCommentGenerator (). addComment (answer); StringBuilder sb = new StringBuilder (); sb.append ( "update"); //$non-nls-1$sb.append(introscedtable.getlyQuiLifiedTablenAmeAtruntime() ;//tag 컨텐츠, 즉 텍스트 요소 답변 (new TextLement (sb.tostring ())); sb.setlength (0); // Set Tag XMLEMENMENT SETELENTE = NEW XMLELEMENT ( "SET"); // $ non-nls-1 $ // 데이터베이스 테이블 목록에서 모든 필드를 가져옵니다. <CLERTROSTECTECHOLUMN> cols = introscedTable.getAllColumns (); // iteration java.util.iterator <IntroctedColumn> iter = cols.ITerator (); = iter.next (); // if tag xmlelement ifelement = new xmlelement ( "if"); // $ non-nls-1 $ // 필드 이름 string str = myBatis3formattingUtilities.getEscapedColumnName (introscedColumnname); // 태그 추가 속성 테스트 인 경우 값은 필드입니다! = NULL 및 FIELD! = 'IFELENT.ADDATTRIBUTE (새 속성 ( "테스트", STR+", NULT+")) 수정할 값을 수정할 값을 필드 SB.Append (myBatis3formattingUtilities.getEscapedColumnName (introscedColumn)); sb.append ( "="); //$non-nls-1$sb.append(mybatis3formattingutiilities.getParameterClause(introscedColumn)); if (iter.hasnext ()) {sb.append ( ',');} // 태그가 위의 텍스트 요소 ifelement.addelement (new Textlement (sb.tostring ()); if (iter.hasnext ()) {sb.setlength (0); outpututiences.xmlint (sb, sb, 1);} setElement.addelement (ifelement);} // 요소 (수정 된 필드 전제 조건) xmlelement wherelement = new xmlelement ( "where"); for (introscedColumn introscedColumn : 소개 primarykeyColumns ()) {// 테이블에 필드를 전송합니다. sb.setlength (0); sb.append (myBatis3formattingUtilities.getEscapedColumnName (introscedColumn)); sb.append ( "="); //$non-nls-1$sb.append(mybatis3formattingutifilities.getParameterColumne(introscedcolumn)); whereelement.addelement (sb.toString ());} // 가장 XML XML XML 요소에서 요소를 추가하는 위치에 대한 요소를 추가합니다. 답변 (Wherelement); if (context.getPlugins (). SQLMAPUPDATEBYPRIMARYKEYWITHOUTBLOBSLEMENMENTERADERATED (답변, introscedTable)) {ParentElement.AdDelement (답);}}} 이 업데이트 방법에 따라 다른 방법을 수정할 수 있습니다.
새 방법을 추가하려면 다음 게시물을 참조하십시오.
http://m.blog.csdn.net/article/details?id=35985705
다음으로 수정 결과를 확인하겠습니다
GeneratorConfig.xml // XML을 먼저 구성하고 src/main/resource/directory <? xml 버전 = "1.0"encoding = "utf-8"?> <! doctype generatorconfiguration public "-// mybatis.org//dtd mybatis Generator 구성 1.0 // en" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <GeneratorConfiguration> <!-구성 파일 소개-> <!-데이터 연결 드라이버 주소를 지정하십시오. 위치 = "e : /eclipse_workspace/testmybatis/mysql-connector-java-5.13-bin.jar"/> <!-데이터베이스의 한 컨텍스트-> <context id = "infoguardian"targetruntime = "mybatis3"> <!-hamil-> <value <-> < "" " 무감각-> <속성 이름 = "suppressDate"value = "true" /> <!-주석 생성 Timestamps를 생성할지 여부-> < /commentGenerator> <!-JDBC Connection-> <jdbcConnection DriverClass = "com.mysql.jdbc.driver" ConnectionUrl = "jdbc : mysql : // localhost : 3306/login? charac value = "false"/> </javatyperesolver> <!-엔터티 클래스 주소 생성-> <javamodelgenerator targetpackage = "pojo"targetproject = "mybatis3"> <!-현재 경로에서 새로운 스키마 계층을 추가할지 여부 : Fase Path Cn.ffcs.test.domain ", true" -> <property name = "enablebpackages"value = "true"/> <!-문자열 유형의 필드를 설정할 때 트림을 호출할지 여부-> <property name = "trimstrings"value = "true"/> </javamodelgenerator> <!-mapxml 파일-> <sqlmapgenerator targetpackage = "mappper" "mybatis3"> 현재 경로 아래의 스키마 계층, 예를 들어 : Fase Path CN.ffcs.test.Test.Test.Domain ", true : cn.ffcs.test.domain". type = "xmlmapper"targetpackage = "mapper"targetproject = "mybatis3"> <!-현재 경로에서 새로운 스키마 계층을 추가할지 여부 : fase 경로 cn.ffcs.test.test.domain ", true : cn.ffcs.test.domain". </javaclientgenerator> <!-테이블 정보 구성, 테이블이 여기에서 생성되지 않으며 해당 테이블 이름을 한 번 변경해야합니다 .-> <table tableName = "로그인"domainObjectName = "로그인"enableCountByExampl = "false"enabledeTectByexample = "false"erouse "</table> </GeneratorConfiguration>
startup.java// 검증을위한 주요 프로그램
패키지 tse; import 정적 org.junit.assert.assertequals; import java.io.file; import java.util.arraylist; import java.util.list; import java.util.list; import org.mybatis.api.mybatisgenerator; import org.mybatis.generator.generator.generator. org.mybatis.generator.config.xml.configurationparser; import org.mybatis.generator.internal.defaultshellcallback; public startup {public static void main (string [] args)) 예외 {list <string> warnings = new arraylist <string> (); file (startup.class.getResource ( "/generatorconfig.xml"). touri ()); configurationparser cp = new configurationparser (경고); configuration config = cp.parseconfiguration (configfile); defaultshellcallcallback shellcallcallcallcallcallcallbback (mybatistator); mybatisgenerator = new mybatisgenerator (config, shellcallback, warnings); mybatisgenerator.generate (null); System.out.println (경고);}} 좋아, startup.java를 실행하십시오
해당 파일은 GeneratorConfig.xml의 구성에 따라 대상 디렉토리에서 생성됩니다.
좋아, 내가 예상 한 것과 같은 결과.
5. 위의 수정 후 포장을 시작합니다.
Maven 프로젝트이므로 Maven3.3.9를 사용하고 Maven 내장 Eclipse를 사용할 수 있지만 어쨌든 마음에 들지 않습니다.
아래는 Maven 프로젝트의 pom.xml 파일 코드입니다.
<? xml version = "1.0"encoding = "utf-8"?> <!-Copyright 2009-2011 Apache 라이센스에 따른 Mybatis Teamlicense, 버전 2.0 ( "라이센스"); 라이센스를 준수하는 것 외에는이 파일을 사용할 수 없습니다. 귀하는 라이센스 Athttp : //www.apache.org/license/license/license/license/license/license-2.0의 라이센스 사본을 얻거나 서면에 동의하는 경우, 라이센스에 따라 소프트웨어 배포는 "보증 적 또는 제한적 지구 및 조건에 따라"IS "에 대한 소프트웨어 배포는 명시 적 또는 조건에 따라 배포됩니다. 라이센스 .--> <!-버전 : $ id : pom.xml 4114 2011-11-27 19 : 03 : 32Z simone.tripodi $-> <project xmlns = "http://maven.apache.org/pom/4.0.0"xmlns : xsi = "http://www.w.w.org/2001/xmlsome" xsi : schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <6odelversion> 4.0.0</modelversion> <<<parent><<<<<<<<<<<< groupid>org.generator</groupid> artifactid> mybati s-generator </artifactid> <3.2 </version> </parent> <artifactid> mybatis-generator-core </artifactid> <packaging> jar </packaging> <name> mybatis Generator Core </name> <빌드> <!-이 빌드는 시스템 프로젝트에서 사용하기 위해 계측 된 JAR 파일을 생성하고 설치하여 통합 범위 정보를 수집 할 수 있습니다-> <플러그인> <!- <Plugin> <groupId> org.apache.maven.plugins </groupid> <artifactid> maven-site-plugin </artifactid> <executions> <executions> <executions> <case> 준비-패키지 </phase> <goving> goal> site </goal> </govent> </execution> </plugin >--> <! <Plugin> <groupId> org.apache.maven.plugins </groupid> <artifactid> maven-source-plugin </artifactid> <executions> <executions> <단계> 준비-패키지 </phase> <goving> <goal> jar-no-fork </gover> </execution> </execution> </plugin>->->->->->->->-> <! <플러그인> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven-source-plugin </artifactid> <bersion> 2.2.1 </version> <executions> <execution> <id> at Tach-Sources </id> <goving> a goal> jar </goal> </goal> </gover> <conclude> <clender> <clender> **/org/** </include> </include> </configuration> </execution> </plugin> -> <!-<flugin> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven-javadoc-plugin </artifactid> <executions> <pase> 준비-패키지 </phase> <goving> <gov </bock </govent> </execution> </plugin> -> <Plugin> <groupId> org.codehaus.mojo </groupid> <artifactid> cobertura-maven-plugin </artifactid> <executions> <id> cobertura-instrument </id> <case> pre-intagration-test </phase> <목표> instrument </goal> </gualge> </gualtion> </plugin> <!- <플러그인> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven-jar-plugin </artifactid> <configuration> <archive> <manifest> < Mainclass> org.mybatis.generator.api.shellrunner </mainclass> </manifest> </archive> </configuration> <executions> <execution> <id> Cober TURA-JAR </id> <case> 통합-테스트 </phase> <goal> <goal> a Goal> jar </goal> </gover> <configuration> <classifier> cobertura </classifier> <classeDirectory> $ {basediir}/generated class/classesDirectura </cobobertupation> </execution> </execution> </execution> </execution> -> <flugin> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven-jar-plugin </artifactid> <bersion> 2.4 </version> <execution> <id> attach-jar </id> <state> integration-test </phase> <GOA l> jar </goal> </gorge> </execution> </executions> <configuration> <archive> <addclasspath> true </addclasspath> <classpathprefix> </classpathprefix> <mainclass> org.mybatis.generator.api.shellrunner </main 클래스> </manifest> </archive> <clener> include> include> ** **/org/** </include> </conture> </configuration> </plugin> <plugin> <groupid> org.apache.maven.plugins </groupid> <tritifactid> maven-install-plugin <exe Cutions> <Execution> <id> Cobertura-Install </id> <cate> 통합-테스트 </phase> <goving> <govet> 설치 </boging> </goals> <configuration> <clasifier> cobertura </clasifier> </configuration> </execution> </executions> </plugin> <!-<flugin> <groupid> org.apache.maven.maven.plugins </groupid> <artifactid> maven-assembly-plugin </artifactid> <configuration> <descriptor> <descriptor> $ {basidentir} /src/main/assmbly/src.xml </descriptor> </descriptor> <executions> <execution> <id> 번들 </id> <goving> <goal> Single </Goal> </Goals> <단계> 패키지 </phase> </execution> </executions> </plugin> -> <플러그인> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven-assembly-plugin </artifactid> <configuration> <ackendasembly id> false </backendasemblyid> <descriptors> <descriptor> $ {basedir} /src/main/assembly/src.xml </descriptor> </descriptors> </configuration> <executions> <execution> <id> make-assembly </id> <case> 패키지 </phase> <goving> <goging> 싱글 </목표> </목표> </execution> </execution> </plugin> <groupId> com.googlecode.maven-gcu-pplugin </groupid> maven-gcu-pplug </ar tifactid> <executions> <executions> <case> 배포 </phase> <goving> <goving> 업로드 </목표> </gover> <업로드> <업로드> <file> $ {project.build.directory}/$ {project.artifactid}-$ {project.version} --bundle.zip> <summate generator $ {project.version} </summary> <labels> <label> featured </label> <label> type-archive </label> <label> Product-Generator </label> <label> 버전-$ {project.version} </label> </labels> </upload> </uploads> </configution>/execution >/plugin> <flugin> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven reelease-plugin </artifactid> <configuration> <athuments>-gupload </argload> </songiguration> </plugin> </bui ld> <보고> <Plugins> <Plugin> <groupId> org.codehaus.mojo </groupid> <artifactid> jdepend-maven-plugin </artifactid> <버전> 2.0-beta-2 </version> </plugin> <groupId> org.codehaus.mojo a-maven-plugin </artifactid> </plugin> </plugins> </reporting> <pectionements> <pectionement> <groupId> log4J </groupId> <artifactid> log4j </artifactid> <cope> 제공 </scope> </dependency> <groupid> <groupid> org.apache.ant </gro upid> <artifactid> ant </artifactid> <scope> 제공 </scope> </dependency> <pectomency> <groupid> junit </groupid> <artifactid> junit> </artifactid> <scope> test </scope> </fexendence> <groupid> <groupId> org.hsqldb </groupid> <artif Actid> hsqldb </artifactid> <scope> test </scope> </fectionency> <prectionement> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven-surefire-plugin </artifactid> <2.12 </depaxency> </fexendencies> <cmm> <Url> https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generat 또는 코어 </url> <conn ETHER-1.3.2/mybatis-generator-core </connection> <developerConnection> scm : svn : https : //mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generator-core </scm> </project> 그런 다음 src/main/어셈블리/src.xml 코드를 수정하십시오
<어셈블리 xmlns = "http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"xmlns : xsi = "http://www.w3.org/200 1/xmlschema-instance "xsi : schemalocation ="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.1.xsd"> <<<<bundle</id> <formats><format>zip</format>/formats> <filesets > <fileset> <clerory> src/main/resource </directory> <outputDirectory>/</outputDirectory> <clenerat> include> Genera orconfig.xml </include> </conture> <excludes> <exclude> log4j.properties </exclude> </exclude> </exclude> </fileset> <fileset> <directory> src/main/scripts </directsory> <outputDirectory>/</outputdirectory> incl ude> run.bat </include> </conture> </fileset> <fileset> <directory> $ {project.build.directory} </directory> <outputDirectory>/</outputDirectory> <clenloint> <cloaty> $ {project.artifactid}-$ {project.version} Leset> <fileset> <directory> $ {project.build.directory} </directory> <outputdirectory>/</outputDirectory> <contact> <clenude> $ {project.artifactid}-$ {project.Version} -sources.jar </contacit> </contembly> 다음으로 SRC/Main/아래에서 새 스크립트 폴더를 만들고 Scripts 폴더에서 새 txt 텍스트 문서를 작성하고 다음 코드를 입력하십시오.
Java -jar mybatis -generator -1.3.2.jar -configfile generatorconfig.xml 초과 작성
정지시키다
파일 이름을 run.bat로 변경하십시오
이 시점에서 포장 및 구성이 완료됩니다.
프로젝트에서 실행을 마우스 오른쪽 버튼으로 클릭하고 목표에 패키지를 입력 할 수 있습니다. 또는 명령 줄에 CMD에 프로젝트 디렉토리를 입력하고 MVN 패키지를 실행하십시오. Maven이 종속 JAR 패키지를 다운로드하기 때문에 처음으로 여기에서 실행하면 오랜 시간을 기다릴 것입니다. 참을성있게 기다리십시오.
포장 후, 프로젝트의 루트 디렉토리의 대상 디렉토리에서 다음 구조가 생성됩니다.
위의 그림에서 우리는 mybatis-generator-core-1.3.2.jar 패키지가 생성되었음을 알 수 있습니다. 다음으로이를 사용하여 GeneratorConfig.xml을 추가하여 원하는 코드를 생성 할 수 있습니다.
코드 수정 프로세스 중에 아무것도 이해하지 못하면 더 많은 소스 코드를 읽으십시오.
자, 결과를 보여주세요
이 기사의 전부입니다!
위의 것은 편집자가 소개 한 Mybatis 리버스 엔지니어링 JAR 패키지의 수정 및 포장에 대한 관련 지식입니다. 나는 그것이 모두에게 도움이되기를 바랍니다!