注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

kangzye的博客

加Q群25382780切磋java,加19360923群研究JavaScript

 
 
 

日志

 
 

Mybatis Generator 生成DAO、Bean、Mapper  

2011-08-29 14:44:03|  分类: mybatis |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
代码生成插件 for Eclipse (版本须高版本,好像是3.3+):http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/
然后还需要在项目的lib下面放入 mybatis generator 的相关jar包
主要且唯一的一个配置文件如下:
<?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 >
    <classPathEntry location="D:/java/userlib/drivers/mysql-connector-java-5.0.4-bin.jar"/>
  <context id="context1" >
      <plugin type="tools.PaginationPlugin"></plugin>
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
     connectionURL="jdbc:mysql://localhost/db_product2"
      userId="root" password="000000" />
    <javaModelGenerator targetPackage="com.mapbar.proj.sys.beans" targetProject="Test" />
    <sqlMapGenerator targetPackage="com.mapbar.proj.sys.maps.mysql" targetProject="Test" />
    <javaClientGenerator targetPackage="com.mapbar.proj.sys.dao" targetProject="Test" type="XMLMAPPER" />
    <table schema="db_product2" tableName="tmenu_path" />
    <table schema="db_product2" tableName="tgroup_role" />
    <table schema="db_product2" tableName="tlist_data" />
    <table schema="db_product2" tableName="tmenu" />
    <table schema="db_product2" tableName="trole" />
    <table schema="db_product2" tableName="trole_permissions" />
    <table schema="db_product2" tableName="tskins" />
  </context>
  <context id="context2" >
      <plugin type="tools.PaginationPlugin"></plugin>
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
     connectionURL="jdbc:mysql://localhost/db_product2"
      userId="root" password="000000" />
    <javaModelGenerator targetPackage="com.mapbar.proj.user.beans" targetProject="Test" />
    <sqlMapGenerator targetPackage="com.mapbar.proj.user.maps.mysql" targetProject="Test" />
    <javaClientGenerator targetPackage="com.mapbar.proj.user.dao" targetProject="Test" type="XMLMAPPER" />
    <table schema="db_product2" tableName="tuser" />
    <table schema="db_product2" tableName="tuser_reserve" />
    <table schema="db_product2" tableName="tuser_role" />
    <table schema="db_product2" tableName="tgroup" />
  </context>
  <context id="context3" >
      <plugin type="tools.PaginationPlugin"></plugin>
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
     connectionURL="jdbc:mysql://localhost/db_product2"
      userId="root" password="000000" />
    <javaModelGenerator targetPackage="com.mapbar.proj.poi.beans" targetProject="Test" />
    <sqlMapGenerator targetPackage="com.mapbar.proj.poi.maps.mysql" targetProject="Test" />
    <javaClientGenerator targetPackage="com.mapbar.proj.poi.dao" targetProject="Test" type="XMLMAPPER" />
    <table schema="db_product2" tableName="tcity" />
    <table schema="db_product2" tableName="tclass" />
    <table schema="db_product2" tableName="tgroupcity" />
    <table schema="db_product2" tableName="tmonthly" />
    <table schema="db_product2" tableName="tpoibaseinfo" />
    <table schema="db_product2" tableName="tpoitype" />
    <table schema="db_product2" tableName="tsalestype" />
    <table schema="db_product2" tableName="ttype" />
    <table schema="db_product2" tableName="ttypevalues" />
  </context>
</generatorConfiguration>

安装好上面说的那个插件后,右击该配置文件,即有相应的mybatis generator 的菜单,选择即可按照配置文件的配置生成代码
注意配置文件红色部分,不是必须的,因为默认mybatis generator 生成的是不带分页的操作,添加上面的分页插件并且将插件类置于项目对应位置后,即可产生可分页的代码
分页插件类:
package tools;
import java.util.List; 
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.mybatis.generator.api.CommentGenerator; 
import org.mybatis.generator.api.IntrospectedTable; 
import org.mybatis.generator.api.PluginAdapter; 
import org.mybatis.generator.api.ShellRunner; 
import org.mybatis.generator.api.dom.java.Field; 
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; 
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.api.dom.xml.Attribute; 
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.TextElement; 
import org.mybatis.generator.api.dom.xml.XmlElement; 
/**
 * <pre>
 * add pagination using mysql limit.
 * This class is only used in ibator code generator.
 * </pre>
 */ 
public class PaginationPlugin extends PluginAdapter { 
    private Logger log = Logger.getLogger(PaginationPlugin.class);
    public PaginationPlugin(){
        Properties properties = new Properties();
          properties.setProperty("log4j.rootCategory", "debug, R");
          properties.setProperty("log4j.appender.R", "org.apache.log4j.RollingFileAppender");
          properties.setProperty("log4j.appender.R.File", "D:/mybatisGenerator.log");//the output file ,you can read from other config file
          properties.setProperty("log4j.appender.R.MaxFileSize", "1024000");//去掉K ,只忍数字
          properties.setProperty("log4j.appender.R.MaxBackupIndex", "2");
          properties.setProperty("log4j.appender.R.layout", "org.apache.log4j.PatternLayout");
          properties.setProperty("log4j.appender.R.layout.ConversionPattern", "%m%n");
          PropertyConfigurator.configure( properties );
    }
    @Override 
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, 
            IntrospectedTable introspectedTable) { 
        // add field, getter, setter for limit clause 
        addLimit(topLevelClass, introspectedTable, "limitStart"); 
        addLimit(topLevelClass, introspectedTable, "limitEnd"); 
        return super.modelExampleClassGenerated(topLevelClass, 
                introspectedTable); 
    }
   
    private String getBlank(int deep){
        String s="";
        for(int i=0; i<deep; i++){
            s+="   ";
        }
        return s;
    }
   
    private void printElement(Element element,int deep){
        if(element instanceof XmlElement){
            XmlElement element2 = (XmlElement)element;
            log.info(getBlank(deep)+"Element Name:"+element2.getName());
            deep += 1;
            for(Element c:element2.getElements()){
                printElement(c,deep);
            }
            deep -=1;
        }else{
            log.info(getBlank(deep)+"Element Type:"+element.getClass().getSimpleName());
        }
       
    }
    @Override 
    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated( 
            XmlElement element, IntrospectedTable introspectedTable) { 
        XmlElement isNotNullElement = new XmlElement("if"); //$NON-NLS-1$ 
        isNotNullElement.addAttribute(new Attribute("test", "limitStart >= 0")); //$NON-NLS-1$ //$NON-NLS-2$ 
        isNotNullElement.addElement(new TextElement("limit ${limitStart} , ${limitEnd}")); 
       
        element.addElement(isNotNullElement);
        return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element, introspectedTable); 
    } 
    private void addLimit(TopLevelClass topLevelClass, 
            IntrospectedTable introspectedTable, String name) { 
        CommentGenerator commentGenerator = context.getCommentGenerator(); 
        Field field = new Field(); 
        field.setVisibility(JavaVisibility.PROTECTED); 
        field.setType(FullyQualifiedJavaType.getIntInstance()); 
        field.setName(name); 
        field.setInitializationString("-1"); 
        commentGenerator.addFieldComment(field, introspectedTable); 
        topLevelClass.addField(field); 
        char c = name.charAt(0); 
        String camel = Character.toUpperCase(c) + name.substring(1); 
        Method method = new Method(); 
        method.setVisibility(JavaVisibility.PUBLIC); 
        method.setName("set" + camel); 
        method.addParameter(new Parameter(FullyQualifiedJavaType 
                .getIntInstance(), name)); 
        method.addBodyLine("this." + name + "=" + name + ";"); 
        commentGenerator.addGeneralMethodComment(method, introspectedTable); 
        topLevelClass.addMethod(method); 
        method = new Method(); 
        method.setVisibility(JavaVisibility.PUBLIC); 
        method.setReturnType(FullyQualifiedJavaType.getIntInstance()); 
        method.setName("get" + camel); 
        method.addBodyLine("return " + name + ";"); 
        commentGenerator.addGeneralMethodComment(method, introspectedTable); 
        topLevelClass.addMethod(method); 
    } 
    /**
     * This plugin is always valid - no properties are required
     */ 
    public boolean validate(List<String> warnings) { 
        return true; 
    } 
    public static void generate() { 
        String config = PaginationPlugin.class.getClassLoader().getResource( 
                "mybatisConfig.xml").getFile(); 
        String[] arg = { "-configfile", config, "-overwrite" }; 
        ShellRunner.main(arg); 
    } 
    public static void main(String[] args) { 
        generate(); 
    } 
}
  评论这张
 
阅读(6216)| 评论(3)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017