欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis逆工程jar包的修改和打包

程序员文章站 2024-03-12 08:51:14
上一篇文章mybatis逆工程的使用主要是讲了mybatis-generator-core-1.3.2.jar的使用,这一篇我要介绍的是,修改jar包代码,实现生成自定义模...

上一篇文章mybatis逆工程的使用主要是讲了mybatis-generator-core-1.3.2.jar的使用,这一篇我要介绍的是,修改jar包代码,实现生成自定义模板。

1.我们从这里可以下载mybatis-generator-core-1.3.2.jar项目源码


2.在eclipse下导入存在的maven项目,file->import

Mybatis逆工程jar包的修改和打包

Mybatis逆工程jar包的修改和打包

选择项目源码位置,点finish完成导入。

Mybatis逆工程jar包的修改和打包

项目目录结构大概这样子。

3.下面我逆工程要生成的mapping和xml格式。

Mybatis逆工程jar包的修改和打包

Mybatis逆工程jar包的修改和打包

Mybatis逆工程jar包的修改和打包

4.开始修改,首先说明一下各目录

Mybatis逆工程jar包的修改和打包

最底边的tse包是我自定义的包,里面是个主类,测试生成的代码是否达到预期标准。

由于这个架包是老外写的,生成的代码风格和我们不大一一样,如果你想修改代码格式,建议你看一下菠萝大象的文章,我这里就不讲代码格式了。


首先,我们先修改逆工程要生成的接口文件mapping的代码,默认情况下有增删改查,我们讲其中一个改方法update吧

比如 我要让生成的mapping中有这样的一个方法 void update(map<string, object> datamap);

就修改org.mybatis.generator.codegen.mybatis3.javamapper.elements包下的updatebyprimarykeywithoutblobsmethodgenerator类,如下:

/*
* copyright 2009 the apache software foundation
*
* licensed under the apache license, version 2.0 (the "license");
* you may not use this file except in compliance with the license.
* you may obtain a copy of the license at
*
* http://www.apache.org/licenses/license-2.0
*
* unless required by applicable law or agreed to in writing, software
* distributed under the license is distributed on an "as is" basis,
* without warranties or conditions of any kind, either express or implied.
* see the license for the specific language governing permissions and
* limitations under the license.
*/
package org.mybatis.generator.codegen.mybatis3.javamapper.elements;
import java.util.set;
import java.util.treeset;
import org.mybatis.generator.api.dom.java.fullyqualifiedjavatype;
import org.mybatis.generator.api.dom.java.interface;
import org.mybatis.generator.api.dom.java.javavisibility;
import org.mybatis.generator.api.dom.java.method;
import org.mybatis.generator.api.dom.java.parameter;
/**
* 
* @author jeff butler
* 
*/
public class updatebyprimarykeywithoutblobsmethodgenerator extends
abstractjavamappermethodgenerator {
public updatebyprimarykeywithoutblobsmethodgenerator() {
super();
}
@override
public void addinterfaceelements(interface interfaze) {
set<fullyqualifiedjavatype> importedtypes = new treeset<fullyqualifiedjavatype>();
fullyqualifiedjavatype parametertype = new fullyqualifiedjavatype(
introspectedtable.getbaserecordtype());
importedtypes.add(parametertype);
//新增一个方法
method method = new method();
//添加方法修饰符public
method.setvisibility(javavisibility.public);
//设置返回值,这里我用的是自定义的void,无返回值方法 getvoidinstance()
//fullyqualifiedjavatype类中可以自定义返回值方法,大家可以自己进去添加
//不想那么麻烦的话,可以 new fullyqualifiedjavatype("void") , 构造函数写上返回类型就行了
method.setreturntype(fullyqualifiedjavatype.getvoidinstance());
//设置方法名,同样可以自己进去看
method.setname(introspectedtable.getupdatebyprimarykeystatementid());
//method.addparameter(new parameter(parametertype, "record")); //$non-nls-1$
fullyqualifiedjavatype maptype=fullyqualifiedjavatype.getmymapinstance();
//方法的参数,这里是map类型的datemap参数
parameter parameter = new parameter(maptype, "datamap");
method.addparameter(parameter);
context.getcommentgenerator().addgeneralmethodcomment(method,
introspectedtable);
addmapperannotations(interfaze, method);
if (context.getplugins()
.clientupdatebyprimarykeywithoutblobsmethodgenerated(method,
interfaze, introspectedtable)) {
interfaze.addimportedtypes(importedtypes);
interfaze.addmethod(method);
}
}
public void addmapperannotations(interface interfaze, method method) {
return;
}
} 

大家可以根据注释来修改。

接下来修改mapping对应的xml中的代码,同样的,这里我只介绍修改update方法,相信看完你就能自己修改其它方法。

就修改org.mybatis.generator.codegen.mybatis3.xmlmapper.elements包下的updatebyprimarykeywithoutblobselementgenerator类,如下:

/*
* copyright 2009 the apache software foundation
*
* licensed under the apache license, version 2.0 (the "license");
* you may not use this file except in compliance with the license.
* you may obtain a copy of the license at
*
* http://www.apache.org/licenses/license-2.0
*
* unless required by applicable law or agreed to in writing, software
* distributed under the license is distributed on an "as is" basis,
* without warranties or conditions of any kind, either express or implied.
* see the license for the specific language governing permissions and
* limitations under the license.
*/
package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;
import java.util.iterator;
import java.util.list;
import org.mybatis.generator.api.introspectedcolumn;
import org.mybatis.generator.api.dom.outpututilities;
import org.mybatis.generator.api.dom.xml.attribute;
import org.mybatis.generator.api.dom.xml.textelement;
import org.mybatis.generator.api.dom.xml.xmlelement;
import org.mybatis.generator.codegen.mybatis3.mybatis3formattingutilities;
/**
* 
* @author jeff butler
* 
*/
public class updatebyprimarykeywithoutblobselementgenerator extends
abstractxmlelementgenerator {
//private boolean issimple;
public updatebyprimarykeywithoutblobselementgenerator(boolean issimple) {
super();
//this.issimple = issimple;
}
@override
public void addelements(xmlelement parentelement) {
//update标签(方法最外层)
xmlelement answer = new xmlelement("update"); //$non-nls-1$
//update标签的属性
answer.addattribute(new attribute(
"id", introspectedtable.getupdatebyprimarykeystatementid())); //$non-nls-1$
answer.addattribute(new attribute("parametertype", //$non-nls-1$
"map"));
//把标签加进去
context.getcommentgenerator().addcomment(answer);
stringbuilder sb = new stringbuilder();
sb.append("update "); //$non-nls-1$
sb.append(introspectedtable.getfullyqualifiedtablenameatruntime());
//标签内容,即文本元素
answer.addelement(new textelement(sb.tostring()));
sb.setlength(0);
//set标签
xmlelement setelement = new xmlelement("set"); //$non-nls-1$
//获取数据库表中的所有字段
list <introspectedcolumn> cols=introspectedtable.getallcolumns();
//迭代
java.util.iterator<introspectedcolumn> iter =cols.iterator();
while (iter.hasnext()) {//迭代
//迭代到某一字段
introspectedcolumn introspectedcolumn = iter.next();
//if标签
xmlelement ifelement = new xmlelement("if"); //$non-nls-1$
//字段名
string str=mybatis3formattingutilities
.getescapedcolumnname(introspectedcolumn);
//if标签添加属性test,值为 字段 !=null and 字段!=''
ifelement.addattribute(new attribute("test",str+" != null and "+str+"!='' "));
//if标签内容 ,文本元素,给字段赋予即将修改的值
sb.append(mybatis3formattingutilities
.getescapedcolumnname(introspectedcolumn));
sb.append(" = "); //$non-nls-1$
sb.append(mybatis3formattingutilities
.getparameterclause(introspectedcolumn));
if (iter.hasnext()) {
sb.append(',');
}
//if标签添加上面的文本元素
ifelement.addelement(new textelement(sb.tostring()));
if (iter.hasnext()) {
sb.setlength(0);
outpututilities.xmlindent(sb, 1);
}
setelement.addelement(ifelement);
}
//where元素(修改的字段前提条件)
xmlelement whereelement =new xmlelement("where");
for (introspectedcolumn introspectedcolumn : introspectedtable
.getprimarykeycolumns()) {//遍历表中字段进行判断
sb.setlength(0);
sb.append(mybatis3formattingutilities
.getescapedcolumnname(introspectedcolumn));
sb.append(" = "); //$non-nls-1$
sb.append(mybatis3formattingutilities
.getparameterclause(introspectedcolumn));
whereelement.addelement(new textelement(sb.tostring()));
}
//方法中最外层xml元素 update元素添加set元素和where元素
answer.addelement(setelement);
answer.addelement(whereelement);
if (context.getplugins()
.sqlmapupdatebyprimarykeywithoutblobselementgenerated(answer,
introspectedtable)) {
parentelement.addelement(answer);
}
}
} 

其它方法大家可以根据这个update方法改。

如果要添加新方法的话参考下面这个帖子


下面我来验证修改成果

generatorconfig.xml //先配置xml 放在src/main/resources/ 目录下
<?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> 
<!-- 引入配置文件 --> 
<!-- 指定数据连接驱动jar地址 --> 
<classpathentry location="e:\eclipse_workspace\testmybatis\mysql-connector-java-5.1.13-bin.jar" /> 
<!-- 一个数据库一个context --> 
<context id="infoguardian" targetruntime="mybatis3"> 
<!-- 注释 --> 
<commentgenerator > 
<property name="suppressallcomments" value="true"/><!-- 是否取消注释 --> 
<property name="suppressdate" value="true" /> <!-- 是否生成注释代时间戳--> 
</commentgenerator> 
<!-- jdbc连接 --> 
<jdbcconnection driverclass="com.mysql.jdbc.driver" 
connectionurl="jdbc:mysql://localhost:3306/login?characterencoding=utf-8" userid="root" 
password="root" /> 
<!-- 类型转换 --> 
<javatyperesolver> 
<!-- 是否使用bigdecimal, false可自动转化以下类型(long, integer, short, etc.) --> 
<property name="forcebigdecimals" value="false"/> 
</javatyperesolver> 
<!-- 生成实体类地址 --> 
<javamodelgenerator targetpackage="pojo" 
targetproject="mybatis3" > 
<!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaname] --> 
<property name="enablesubpackages" value="true"/> 
<!-- 是否针对string类型的字段在set的时候进行trim调用 --> 
<property name="trimstrings" value="true"/> 
</javamodelgenerator> 
<!-- 生成mapxml文件 --> 
<sqlmapgenerator targetpackage="mapper" 
targetproject="mybatis3" > 
<!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaname] --> 
<property name="enablesubpackages" value="true" /> 
</sqlmapgenerator> 
<!-- 生成mapxml对应client,也就是接口dao --> 
<javaclientgenerator type="xmlmapper" targetpackage="mapper" 
targetproject="mybatis3"> 
<!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaname] --> 
<property name="enablesubpackages" value="true" /> 
</javaclientgenerator> 
<!-- 配置表信息,这里没生成一张表,这里需要改变一次对应表名 --> 
<table tablename="login" 
domainobjectname="login" enablecountbyexample="false" 
enabledeletebyexample="false" enableselectbyexample="false" 
enableupdatebyexample="false"> 
</table> 
</context> 
</generatorconfiguration> 

startup.java//验证的主程序

package tse;
import static org.junit.assert.assertequals;
import java.io.file;
import java.util.arraylist;
import java.util.list;
import org.mybatis.generator.api.mybatisgenerator;
import org.mybatis.generator.config.configuration;
import org.mybatis.generator.config.xml.configurationparser;
import org.mybatis.generator.internal.defaultshellcallback;
public class startup {
public static void main(string []args)throws exception{
list<string> warnings = new arraylist<string>();
file configfile=new file(startup.class.getresource("/generatorconfig.xml").touri());
configurationparser cp = new configurationparser(warnings);
configuration config = cp.parseconfiguration(configfile);
defaultshellcallback shellcallback = new defaultshellcallback(true);
mybatisgenerator mybatisgenerator = new mybatisgenerator(config, shellcallback, warnings);
mybatisgenerator.generate(null);
system.out.println(warnings);
}
} 

好了,运行startup.java

Mybatis逆工程jar包的修改和打包

就根据generatorconfig.xml的配置在目标目录生成对应文件。

ok,和我预期结果一样。

5.上面修改完了,我们开始打包。

由于是个maven项目,我用的是maven3.3.9,大家也可以用eclipse内置的maven,反正我是不喜欢。

下面是我maven项目的pom.xml文件代码

<?xml version="1.0" encoding="utf-8"?>
<!--
copyright 2009-2011 the mybatis team
licensed under the apache license, version 2.0 (the "license");
you may not use this file except in compliance with the license.
you may obtain a copy of the license at
http://www.apache.org/licenses/license-2.0
unless required by applicable law or agreed to in writing, software
distributed under the license is distributed on an "as is" basis,
without warranties or conditions of any kind, either express or implied.
see the license for the specific language governing permissions and
limitations under the license.
-->
<!--
version: $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.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelversion>4.0.0</modelversion>
<parent>
<groupid>org.mybatis.generator</groupid>
<artifactid>mybatis-generator</artifactid>
<version>1.3.2</version>
</parent>
<artifactid>mybatis-generator-core</artifactid>
<packaging>jar</packaging>
<name>mybatis generator core</name>
<build>
<!-- this build creates and installs an instrumented jar file
for use by the systests projects - so we can gather
consolidated coverage information
-->
<plugins>
<!-- <plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-site-plugin</artifactid>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>site</goal>
</goals>
</execution>
</executions>
</plugin> -->
<!-- <plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-source-plugin</artifactid>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin> -->
<!-- <plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-source-plugin</artifactid>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<includes>
<include>**/org/**</include>
</includes>
</configuration>
</execution>
</executions>
</plugin> -->
<!-- <plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-javadoc-plugin</artifactid>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin> -->
<plugin>
<groupid>org.codehaus.mojo</groupid>
<artifactid>cobertura-maven-plugin</artifactid>
<executions>
<execution>
<id>cobertura-instrument</id>
<phase>pre-integration-test</phase>
<goals>
<goal>instrument</goal>
</goals>
</execution>
</executions> 
</plugin>
<!-- <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>cobertura-jar</id>
<phase>integration-test</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>cobertura</classifier>
<classesdirectory>${basedir}/target/generated-classes/cobertura</classesdirectory>
</configuration>
</execution>
</executions>
</plugin> -->
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-jar-plugin</artifactid>
<version>2.4</version>
<executions>
<execution>
<id>attach-jar</id>
<phase>integration-test</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addclasspath>true</addclasspath>
<classpathprefix></classpathprefix>
<mainclass>org.mybatis.generator.api.shellrunner</mainclass>
</manifest>
</archive>
<includes>
<include>**/org/**</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-install-plugin</artifactid>
<executions>
<execution>
<id>cobertura-install</id>
<phase>integration-test</phase>
<goals>
<goal>install</goal>
</goals>
<configuration>
<classifier>cobertura</classifier>
</configuration>
</execution>
</executions> 
</plugin>
<!-- <plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-assembly-plugin</artifactid>
<configuration>
<descriptors>
<descriptor>${basedir}/src/main/assembly/src.xml</descriptor>
</descriptors>
</configuration> 
<executions>
<execution>
<id>bundle</id>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin> -->
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-assembly-plugin</artifactid>
<configuration>
<appendassemblyid>false</appendassemblyid>
<descriptors>
<descriptor>${basedir}/src/main/assembly/src.xml</descriptor>
</descriptors>
</configuration> 
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupid>com.googlecode.maven-gcu-plugin</groupid>
<artifactid>maven-gcu-plugin</artifactid>
<executions>
<execution>
<phase>deploy</phase>
<goals>
<goal>upload</goal>
</goals>
<configuration>
<uploads>
<upload>
<file>${project.build.directory}/${project.artifactid}-${project.version}-bundle.zip</file>
<summary>mybatis generator ${project.version}</summary>
<labels>
<label>featured</label>
<label>type-archive</label>
<label>product-generator</label>
<label>version-${project.version}</label>
</labels>
</upload>
</uploads>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-release-plugin</artifactid>
<configuration>
<arguments>-prelease,gupload</arguments>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupid>org.codehaus.mojo</groupid>
<artifactid>jdepend-maven-plugin</artifactid>
<version>2.0-beta-2</version>
</plugin>
<plugin>
<groupid>org.codehaus.mojo</groupid>
<artifactid>cobertura-maven-plugin</artifactid>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupid>log4j</groupid>
<artifactid>log4j</artifactid>
<scope>provided</scope>
</dependency>
<dependency>
<groupid>org.apache.ant</groupid>
<artifactid>ant</artifactid>
<scope>provided</scope>
</dependency>
<dependency>
<groupid>junit</groupid>
<artifactid>junit</artifactid>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.hsqldb</groupid>
<artifactid>hsqldb</artifactid>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-surefire-plugin</artifactid>
<version>2.12</version>
</dependency>
</dependencies>
<scm>
<url>https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-1.3.2/mybatis-generator-core</url>
<connection>scm:svn:https://mybatis.googlecode.com/svn/sub-projects/generator/tags/mybatis-generator-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</developerconnection>
</scm> 
</project> 

然后是修改src/main/assembly/src.xml代码

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>bundle</id>
<formats>
<format>zip</format>
</formats>
<filesets>
<fileset>
<directory>src/main/resources</directory>
<outputdirectory>/</outputdirectory>
<includes>
<include>generatorconfig.xml</include>
</includes>
<excludes>
<exclude>log4j.properties</exclude>
<exclude>src.xml</exclude>
</excludes>
</fileset>
<fileset>
<directory>src/main/scripts</directory>
<outputdirectory>/</outputdirectory>
<includes>
<include>run.bat</include>
</includes>
</fileset>
<fileset>
<directory>${project.build.directory}</directory>
<outputdirectory>/</outputdirectory>
<includes>
<include>${project.artifactid}-${project.version}.jar</include>
</includes>
</fileset>
<fileset>
<directory>${project.build.directory}</directory>
<outputdirectory>/</outputdirectory>
<includes>
<include>${project.artifactid}-${project.version}-sources.jar</include>
</includes>
</fileset>
</filesets>
</assembly> 

接下来,在src/main/ 下面新建scripts文件夹,在scripts文件夹新建txt文本文档,输入以下代码

java -jar mybatis-generator-1.3.2.jar -configfile generatorconfig.xml –overwrite
pause

改文件名为run.bat

至此,打包配置完毕。

大家可以在项目下右键run as->maven build 在goal里输入package。或者命令行cmd中 进入项目的目录,运行mvn package,这里第一次运行会等待很久,因为maven会下载依赖的jar包,请耐心等待。

打包完毕,就会在项目根目录下的target目录生成如下结构

Mybatis逆工程jar包的修改和打包

从上图中我们可以看到mybatis-generator-core-1.3.2.jar包已经生成。接下来我们可以用它加上generatorconfig.xml来生成自己想要的代码。

如果修改代码过程中有什么不懂的,请多看源代码。

ok,晒下成果图

Mybatis逆工程jar包的修改和打包Mybatis逆工程jar包的修改和打包

本文就讲到这里!

以上所述是小编给大家介绍的mybatis逆工程jar包的修改和打包的相关知识,希望对大家有所帮助!