`
yangjayup
  • 浏览: 253549 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Mybatis Generator自动生成Mybatis相关代码

 
阅读更多


 

 

 

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 MapperPaginationPlugin extends PluginAdapter { 
    private Logger log = Logger.getLogger(PaginationPlugin.class);
    public MapperPaginationPlugin(){
        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, "limitMaxSize"); 
        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} , ${limitMaxSize}")); 
       
        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(); 
    } 
}

 

 

 

import java.util.List;

import org.mybatis.generator.api.PluginAdapter;

import java.util.List;
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.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 {
    @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);
    }

    @Override
    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(
            XmlElement element, IntrospectedTable introspectedTable) {
        XmlElement isParameterPresenteElemen = (XmlElement) element
                .getElements().get(element.getElements().size() - 1);
        XmlElement isNotNullElement = new XmlElement("isGreaterEqual"); //$NON-NLS-1$  
        isNotNullElement.addAttribute(new Attribute("property", "limitStart")); //$NON-NLS-1$ //$NON-NLS-2$  
        isNotNullElement.addAttribute(new Attribute("compareValue", "0")); //$NON-NLS-1$ //$NON-NLS-2$  
        isNotNullElement.addElement(new TextElement(
                "limit $limitStart$ , $limitEnd$"));
        isParameterPresenteElemen.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("Yododo.xml").getFile();
        String[] arg = { "-configfile", config, "-overwrite" };
        ShellRunner.main(arg);
    }

    public static void main(String[] args) {
        generate();
    }
}

 

 

 

targetProject=mybatis-generatorByMaven
#targetProject=Yododo
model.package=com.yododo.core.domain
sqlMap.package=sqlmap.mybatis
dao.package=com.yododo.core.dao.mybatis
jdbc.jar=C:/Users/Administrator/.m2/repository/mysql/mysql-connector-java/5.1.18/mysql-connector-java-5.1.18.jar
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://192.168.1.5\:3306/yddtest?useUnicode\=true&amp;characterEncoding\=UTF-8
jdbc.user=ydd
jdbc.password=MySqL4ydd

 

 

 

 

<?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>
	<properties resource="mybatis.properties" />
	<classPathEntry
		location="D:\Projects\tour\lib\mysql-connector-java-5.1.18-bin.jar" />
  <!-- MyBatis3  Ibatis2Java5 -->
	<context id="context1" targetRuntime="MyBatis3">
		<plugin type="MapperPaginationPlugin" />
		<commentGenerator>
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="${jdbc.url}" userId="${jdbc.user}" password="${jdbc.password}" />
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>
		<javaModelGenerator targetPackage="${model.package}"
			targetProject="${targetProject}">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<sqlMapGenerator targetPackage="${sqlMap.package}"
			targetProject="${targetProject}">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
    <!-- SPRING  XMLMAPPER -->
		<javaClientGenerator type="XMLMAPPER" targetPackage="${dao.package}"
			targetProject="${targetProject}">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		
		<!-- <table tableName="tour_place_range">
      <generatedKey column="place_range_id" identity="true"
        sqlStatement="SELECT LAST_INSERT_ID()"></generatedKey>
    </table> -->
		
		<table tableName="sale_hotel">
		  <columnOverride column="status" javaType="Integer" jdbcType="TINYINT"></columnOverride>
		  <columnOverride column="securepay" javaType="Integer" jdbcType="TINYINT"></columnOverride>
		  <columnOverride column="areaorderid" javaType="Integer" jdbcType="TINYINT"></columnOverride>
		  <columnOverride column="pricefrom" javaType="Integer" jdbcType="SMALLINT"></columnOverride>
		  <columnOverride column="priceto" javaType="Integer" jdbcType="SMALLINT"></columnOverride>
		</table>
		
	</context>
		 
</generatorConfiguration>

 

 

MyEclipse下右击Yododo.xml点Generate Mybatis/iBATIS Artifacts 运行生成

 

MyEclipse

增加generatorByMaven插件地址:http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite

手工添加:将附件中解压的features和plugins文件夹里的内容分别拷贝到MyEclipse的features和plugins文件夹后重启myeclipse即可

 

mac系统eclipse安装

手动安装:将附件中解压的features和plugins文件夹拷贝到Eclipse安装目录的dropins文件夹下重启eclipse即可

 

 

 

  • 大小: 81.2 KB
分享到:
评论

相关推荐

    mybatis-generator自动生成代码[增加Service的生成]

    总结来说,MyBatis Generator是一个强大的代码生成工具,它能自动生成包括Service在内的持久层代码,大大简化了开发过程。通过定制配置和模板,开发者可以根据项目需求调整生成的代码结构和风格,提升开发效率,同时...

    使用Mybatis Generator自动生成Mybatis相关代码

    总之,Mybatis Generator是Mybatis框架下的一款强大辅助工具,它通过自动化代码生成,帮助开发者节省大量手动编写基础代码的时间,提高了开发效率,降低了出错概率。熟练掌握Mybatis Generator的使用,能让你在...

    MyBatis Generator 自动生成代码完整包

    MyBatis Generator(MBG)是一款强大的工具,用于自动生成MyBatis框架的SQL映射文件、Java模型类以及DAO接口。它极大地提高了开发效率,减少了手动编写这些基础代码的工作量,使开发者能够更专注于业务逻辑的实现。...

    使用MyBatis Generator自动生成MyBatis代码.docx

    MyBatis Generator 是一个基于 MyBatis 的代码生成工具,能够根据数据库表结构生成相应的 MyBatis 代码,包括实体类、映射文件、DAO 层和 Service 层等。使用 MyBatis Generator 可以大大减少开发时间和工作量,提高...

    mybatis generator自动生成DAO、Bean、MapperXML等文件

    MyBatis Generator(MBG)是一款强大的自动化代码生成工具,专为MyBatis框架设计,能够自动生成DAO层、实体Bean以及Mapper XML文件,极大地提高了开发效率。在使用MBG时,用户只需要进行简单的配置,就可以自动生成...

    使用Mybatis Generator自动生成Mybatis相关代码(包含Mysql与Oracle)

    本教程将详细讲解如何使用Mybatis Generator针对Mysql和Oracle数据库自动生成相关代码。 首先,我们需要了解Mybatis Generator的基本配置。在项目中创建一个`generatorConfig.xml`配置文件,这是Mybatis Generator...

    Mybatis Generator 代码生成工具

    Mybatis Generator 是一款强大的自动化代码生成工具,它能够极大提高开发效率,特别是在处理与数据库交互的 CRUD(创建、读取、更新、删除)操作时。这个工具能够自动生成 Mybatis 的 XML 映射文件、实体类以及 ...

    Mybatis Generator自动生成JavaEntity带中文注释和注解[Maven]工程

    在"Maven"环境下,我们可以轻松地集成这个插件,实现自动化代码生成,尤其对于处理带有中文注释和注解的需求,Mybatis Generator提供了很好的解决方案。 首先,我们来详细了解一下Mybatis Generator的配置过程。你...

    MyBatis Generator代码自动生成

    MyBatis Generator是一款强大的工具,它能够自动生成MyBatis框架所需的SQL映射文件、实体类和DAO接口,极大地提高了开发效率。通过重写MyBatis Generator的源码,我们可以进一步定制化生成的代码,使其更符合项目...

    mybatis-generator生成sqlserver数据库Bean、Dao、Mapper代码工具

    MyBatis Generator(MBG)是一款强大的自动化代码生成工具,主要针对MyBatis框架,能够帮助开发者自动生成Java Bean、DAO层以及Mapper XML文件,极大地提高了开发效率,减少了手动编写这些重复性工作的时间。...

    mybatis-generator 自动生成mybatis dao model层代码

    mybatis-generator 自动生成mybatis dao model层代码

    Mybatis Generator自动生成代码demo

    Mybatis Generator是一个基于Java的代码生成器,它通过读取数据库表结构信息,根据预设的模板生成相应的Java代码。主要涉及的元素包括配置文件、模型类、XML映射文件和Mapper接口。 配置文件是Mybatis Generator的...

    IntelliJ IDEA Maven Mybatis generator 自动生成代码

    这是 IntelliJ IDEA Maven Mybatis generator 自动生成代码 的完整源码 教程地址:http://blog.csdn.net/fenglailea/article/details/78291522

    MybatisGenerator代码生成器(可查询指定字段)

    MybatisGenerator本身是没有提供查询指定字段的,例如数据库有5个字段,我想查询其中3个...经过研究MybatisGenerator实现原理,在保证原有功能的基础上,实现了生成查询指定字段的相关方法,下载即可使用。eclipse!

    mybatis 代码自动生成 ,并且自定义注释结合swagger

    首先,MyBatis的代码生成器(MyBatis Generator,简称MBG)能够自动生成Mapper接口、Mapper XML文件、实体类以及对应的DAO层代码,大大减少了手动编写这些基础代码的时间。通过自定义MBG的配置文件,我们可以定制...

    MyBatis-Generator 自动生成Lombok标签 不生成Get/Set方法

    把下载的jar包放在 Maven仓库的 org\mybatis\generator\mybatis-generator-core\1.3.5 下面即可,然后在generatorConfig配置文件中加上&lt;plugin type="org.mybatis.generator.plugins.LombokPlugin" &gt; &lt;/plugin&gt; ...

Global site tag (gtag.js) - Google Analytics