mybatis-generator在eclipse maven环境下使用

1.在工程中创建公共maven quick-start项目,在此命名为simcommon,该项目只提供公共的pom,修改pom代码如下

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.simon.common</groupId>
    <artifactId>simcommon</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>simcommon</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.1.2.RELEASE</spring.version>
        <mysql.version>5.1.13</mysql.version>
        <mybatis-generator.version>1.3.1</mybatis-generator.version>
        <mybatis.version>3.2.6</mybatis.version>
        <cfx.version>3.0.0</cfx.version>
    </properties>

    <dependencyManagement>
        <dependencies>

            <dependency>
                <groupId>net.erdfelt.android</groupId>
                <artifactId>apk-parser</artifactId>
                <version>1.1</version>
            </dependency>

            <!-- json相关包 -->
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-asl</artifactId>
                <version>1.9.13</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>1.9.13</version>
            </dependency>
            <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <version>2.4</version>
            </dependency>

            <dependency>
                <groupId>cglib</groupId>
                <artifactId>cglib-nodep</artifactId>
                <version>3.1</version>
            </dependency>

            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcprov-jdk16</artifactId>
                <version>1.46</version>
            </dependency>

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
                <version>5.1.3.Final</version>
            </dependency>

            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
            <dependency>
                <groupId>commons-lang</groupId>
                <artifactId>commons-lang</artifactId>
                <version>2.6</version>
            </dependency>
            <dependency>
                <groupId>commons-collections</groupId>
                <artifactId>commons-collections</artifactId>
                <version>3.2.1</version>
            </dependency>
            <dependency>
                <groupId>com.caucho</groupId>
                <artifactId>hessian</artifactId>
                <version>4.0.38</version>
            </dependency>
            <dependency>
                <groupId>commons-net</groupId>
                <artifactId>commons-net</artifactId>
                <version>3.3</version>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.7.2</version>
            </dependency>

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxws</artifactId>
                <version>${cfx.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-transports-http</artifactId>
                <version>${cfx.version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.openejb</groupId>
                <artifactId>javaee-api</artifactId>
                <version>5.0-1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.faces</groupId>
                <artifactId>jsf-api</artifactId>
                <version>1.2_04</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.faces</groupId>
                <artifactId>jsf-impl</artifactId>
                <version>1.2_04</version>
                <scope>provided</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.1.3</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-access</artifactId>
                <version>1.1.3</version>
            </dependency>

            <!-- mybaits -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>${mybatis-generator.version}</version>
            </dependency>

            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>

            <!-- JDBC连接数据库所需依赖 -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>com.springsource.org.apache.commons.dbcp</artifactId>
                <version>1.2.2.osgi</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.2.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.32</version>
            </dependency>

            <!-- test start -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>6.9.4</version>
            </dependency>
            <!-- test end -->

        </dependencies>

    </dependencyManagement>
</project>

  以上为项目中一些常用包的配置,在此内容内基本没有用到,可根据实际情况进行删减或添加

2.重复上述步骤,创建新maven-quickstart分页插件项目,该项目主要用于分页代码的生成,如怕麻烦可以不创建,直接跳到步骤4,这里手动修改xml mapper即可,在此命名为simmbgenerator,修改pom文件

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.simon</groupId>
    <artifactId>simmbgenerator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>simmbgenerator</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.1</version>
            <type>jar</type>
        </dependency>
    </dependencies>
</project>

3.添加分页类,这里用的是mysql,所以用的是mysql的分页类,因为查询条件自己写了类,所以以下代码只提供生成limitStart和limitEnd功能,其他数据库可以从网上自行查找

package com.simon.utility.tool;

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.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;

public class MySQLPaginationPlugin extends PluginAdapter {
    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
            IntrospectedTable introspectedTable) { // add field, getter, setter
                                                    // for limit clause
        return super.modelExampleClassGenerated(topLevelClass,
                introspectedTable);
    }

    @Override
    public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(
            XmlElement element, IntrospectedTable introspectedTable) {
        XmlElement page = new XmlElement("if");
        page.addAttribute(new Attribute("test", "limitStart != null and limitStart>=0"));
        page.addElement(new TextElement("limit #{limitStart} , #{limitEnd}"));
        element.addElement(page);
        return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element,
                introspectedTable);
    }

    /**
     * This plugin is always valid - no properties are required
     */
    public boolean validate(List<String> warnings) {
        return true;
    }
}

4.右键pom->runas -> maven build输入clean install将jar包打入maven库

5.新建需要生成代码的maven-quickstart项目,修改pom文件如下

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.simon.dal</groupId>
    <artifactId>simdal</artifactId>
    <packaging>jar</packaging>

    <name>simdal</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- test start -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- test end -->

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
        </dependency>
    </dependencies>

    <parent>
        <groupId>com.simon.common</groupId>
        <artifactId>simon_common</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../simon_common</relativePath>
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>

                <configuration>
                    <configurationFile>src/test/resources/mybatis-generator/generator-config.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>

                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.32</version>
                    </dependency>
                    <dependency>
                        <groupId>com.simon</groupId>
                        <artifactId>simmbgenerator</artifactId>
                        <version>0.0.1-SNAPSHOT</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

6.在上面配置的<configurationFile>src/test/resources/mybatis-generator/generator-config.xml</configurationFile>路径中添加该文件,内容如下

<?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>
  <!-- clas<font size="" color=""></font>sPathEntry:数据库的JDBC驱动 -->
  <!-- <classPathEntry location="D:\maven_data\mvn_repository\mysql\mysql-connector-java\5.1.32\mysql-connector-java-5.1.32.jar" /> -->

  <context id="DB2Tables" targetRuntime="MyBatis3">

        <!-- 这里引入扩展插件,用于分页 -->
      <plugin type="com.simon.utility.tool.MySQLPaginationPlugin" />

      <!-- 去除自动生成的注释 -->
      <commentGenerator>
       <property name="suppressAllComments" value="true" />
      </commentGenerator>

      <!-- 数据库的url 用户名 密码-->
      <jdbcConnection driverClass="com.mysql.jdbc.Driver"
         connectionURL="jdbc:mysql://192.168.112.128:3306/simon_user"
         userId="admin"
         password="password">
      </jdbcConnection>

      <javaTypeResolver >
       <property name="forceBigDecimals" value="false" />
      </javaTypeResolver>

      <!-- 生成模型的包名和位置:自动生成代码的位置, -->
      <javaModelGenerator targetPackage="com.simon.model" targetProject="src/main/java">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />
      </javaModelGenerator>

      <!-- 自动生成映射文件的包名和位置 -->
      <sqlMapGenerator targetPackage="mybatis-mapper" targetProject="src/main/resources">
        <property name="enableSubPackages" value="true" />
      </sqlMapGenerator>
      <!-- 生成Dao 的包名和位置  -->
      <javaClientGenerator type="XMLMAPPER" targetPackage="com.simon.dao" targetProject="src/main/java">
        <property name="enableSubPackages" value="true" />
      </javaClientGenerator>

      <!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->
      <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
      <table tableName="simon_area_info" domainObjectName="AreaInfo" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true"/>

  </context>

</generatorConfiguration>

7.右键pom->runas -> maven build,输入mybatis-generator:generate生成代码

在此,我对生成的代码进行了修改,以我城市列表数据库为例,修改后的代码如下

7.1数据库结构

/*创建地区列表*/
create table simon_user.simon_area_info
(
    id integer unsigned auto_increment not null primary key COMMENT ‘地区id‘,
    category varchar(16) unsigned not null COMMENT ‘类型‘,
    code integer unsigned not null COMMENT ‘编号‘,
    parent_code integer unsigned not null COMMENT ‘父地区编号‘,
    area_name varchar(32) not null COMMENT ‘名称‘,
    enabled integer unsigned default 1 not null COMMENT ‘是否展示‘,
    sort_code integer unsigned default 1 not null COMMENT ‘排序‘,
    create_time datetime not null default now() COMMENT ‘创建时间‘,
    create_user_id bigint not null default 1 COMMENT ‘创建人‘,
    update_time datetime null COMMENT ‘修改时间‘,
    update_user_id bigint null COMMENT ‘修改人‘
) ENGINE=MyISAM;
alter table simon_user.simon_area_info add INDEX index_code(code);
alter table simon_user.simon_area_info add INDEX index_parent_code(parent_code); 

7.2 mapper.xml文件修改后内容,在此只做了两点修改,1.将Example_Where_Clause和Update_Example_Where_Clause修改为Where_Clause,将Example修改为FilterCondition,其中查询语句

    <if test="limitStart != null and limitStart>=0" >
      limit #{limitStart} , #{limitEnd}
    </if>代码即为分页插件生成
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.simon.dao.AreaInfoMapper" >
  <resultMap id="BaseResultMap" type="com.simon.model.AreaInfo" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="category" property="category" jdbcType="VARCHAR" />
    <result column="code" property="code" jdbcType="INTEGER" />
    <result column="parent_code" property="parentCode" jdbcType="INTEGER" />
    <result column="area_name" property="areaName" jdbcType="VARCHAR" />
    <result column="enabled" property="enabled" jdbcType="INTEGER" />
    <result column="sort_code" property="sortCode" jdbcType="INTEGER" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="create_user_id" property="createUserId" jdbcType="BIGINT" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
    <result column="update_user_id" property="updateUserId" jdbcType="BIGINT" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    id, category, code, parent_code, area_name, enabled, sort_code, create_time, create_user_id,
    update_time, update_user_id
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.simon.model.AreaInfoExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    ‘true‘ as QUERYID,
    <include refid="Base_Column_List" />
    from simon_area_info
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
    <if test="limitStart != null and limitStart>=0" >
      limit #{limitStart} , #{limitEnd}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from simon_area_info
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from simon_area_info
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.simon.model.AreaInfoExample" >
    delete from simon_area_info
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.simon.model.AreaInfo" >
    insert into simon_area_info (id, category, code,
      parent_code, area_name, enabled,
      sort_code, create_time, create_user_id,
      update_time, update_user_id)
    values (#{id,jdbcType=INTEGER}, #{category,jdbcType=VARCHAR}, #{code,jdbcType=INTEGER},
      #{parentCode,jdbcType=INTEGER}, #{areaName,jdbcType=VARCHAR}, #{enabled,jdbcType=INTEGER},
      #{sortCode,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{createUserId,jdbcType=BIGINT},
      #{updateTime,jdbcType=TIMESTAMP}, #{updateUserId,jdbcType=BIGINT})
  </insert>
  <insert id="insertSelective" parameterType="com.simon.model.AreaInfo" >
    insert into simon_area_info
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="category != null" >
        category,
      </if>
      <if test="code != null" >
        code,
      </if>
      <if test="parentCode != null" >
        parent_code,
      </if>
      <if test="areaName != null" >
        area_name,
      </if>
      <if test="enabled != null" >
        enabled,
      </if>
      <if test="sortCode != null" >
        sort_code,
      </if>
      <if test="createTime != null" >
        create_time,
      </if>
      <if test="createUserId != null" >
        create_user_id,
      </if>
      <if test="updateTime != null" >
        update_time,
      </if>
      <if test="updateUserId != null" >
        update_user_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="category != null" >
        #{category,jdbcType=VARCHAR},
      </if>
      <if test="code != null" >
        #{code,jdbcType=INTEGER},
      </if>
      <if test="parentCode != null" >
        #{parentCode,jdbcType=INTEGER},
      </if>
      <if test="areaName != null" >
        #{areaName,jdbcType=VARCHAR},
      </if>
      <if test="enabled != null" >
        #{enabled,jdbcType=INTEGER},
      </if>
      <if test="sortCode != null" >
        #{sortCode,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="createUserId != null" >
        #{createUserId,jdbcType=BIGINT},
      </if>
      <if test="updateTime != null" >
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateUserId != null" >
        #{updateUserId,jdbcType=BIGINT},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.simon.model.AreaInfoExample" resultType="java.lang.Integer" >
    select count(*) from simon_area_info
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update simon_area_info
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.category != null" >
        category = #{record.category,jdbcType=VARCHAR},
      </if>
      <if test="record.code != null" >
        code = #{record.code,jdbcType=INTEGER},
      </if>
      <if test="record.parentCode != null" >
        parent_code = #{record.parentCode,jdbcType=INTEGER},
      </if>
      <if test="record.areaName != null" >
        area_name = #{record.areaName,jdbcType=VARCHAR},
      </if>
      <if test="record.enabled != null" >
        enabled = #{record.enabled,jdbcType=INTEGER},
      </if>
      <if test="record.sortCode != null" >
        sort_code = #{record.sortCode,jdbcType=INTEGER},
      </if>
      <if test="record.createTime != null" >
        create_time = #{record.createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="record.createUserId != null" >
        create_user_id = #{record.createUserId,jdbcType=BIGINT},
      </if>
      <if test="record.updateTime != null" >
        update_time = #{record.updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="record.updateUserId != null" >
        update_user_id = #{record.updateUserId,jdbcType=BIGINT},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update simon_area_info
    set id = #{record.id,jdbcType=INTEGER},
      category = #{record.category,jdbcType=VARCHAR},
      code = #{record.code,jdbcType=INTEGER},
      parent_code = #{record.parentCode,jdbcType=INTEGER},
      area_name = #{record.areaName,jdbcType=VARCHAR},
      enabled = #{record.enabled,jdbcType=INTEGER},
      sort_code = #{record.sortCode,jdbcType=INTEGER},
      create_time = #{record.createTime,jdbcType=TIMESTAMP},
      create_user_id = #{record.createUserId,jdbcType=BIGINT},
      update_time = #{record.updateTime,jdbcType=TIMESTAMP},
      update_user_id = #{record.updateUserId,jdbcType=BIGINT}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.simon.model.AreaInfo" >
    update simon_area_info
    <set >
      <if test="category != null" >
        category = #{category,jdbcType=VARCHAR},
      </if>
      <if test="code != null" >
        code = #{code,jdbcType=INTEGER},
      </if>
      <if test="parentCode != null" >
        parent_code = #{parentCode,jdbcType=INTEGER},
      </if>
      <if test="areaName != null" >
        area_name = #{areaName,jdbcType=VARCHAR},
      </if>
      <if test="enabled != null" >
        enabled = #{enabled,jdbcType=INTEGER},
      </if>
      <if test="sortCode != null" >
        sort_code = #{sortCode,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="createUserId != null" >
        create_user_id = #{createUserId,jdbcType=BIGINT},
      </if>
      <if test="updateTime != null" >
        update_time = #{updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateUserId != null" >
        update_user_id = #{updateUserId,jdbcType=BIGINT},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.simon.model.AreaInfo" >
    update simon_area_info
    set category = #{category,jdbcType=VARCHAR},
      code = #{code,jdbcType=INTEGER},
      parent_code = #{parentCode,jdbcType=INTEGER},
      area_name = #{areaName,jdbcType=VARCHAR},
      enabled = #{enabled,jdbcType=INTEGER},
      sort_code = #{sortCode,jdbcType=INTEGER},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      create_user_id = #{createUserId,jdbcType=BIGINT},
      update_time = #{updateTime,jdbcType=TIMESTAMP},
      update_user_id = #{updateUserId,jdbcType=BIGINT}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

7.3删除类Example类,添加FilterCondition类,该类可通用

package com.simon.util;

import java.util.ArrayList;
import java.util.List;

public class FilterCondition {
    private String orderByClause;

    private boolean distinct;

    private Integer limitStart;

    private Integer limitEnd;

    private List<Criteria> criterias;  

    public FilterCondition(){
        criterias = new ArrayList<Criteria>();
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public Integer getLimitStart() {
        return limitStart;
    }

    public void setLimitStart(Integer limitStart) {
        this.limitStart = limitStart;
    }

    public Integer getLimitEnd() {
        return limitEnd;
    }

    public void setLimitEnd(Integer limitEnd) {
        this.limitEnd = limitEnd;
    }

    public List<Criteria> getCriterias() {
        return criterias;
    }

    public void setCriterias(List<Criteria> criterias) {
        this.criterias = criterias;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (criterias.size() == 0) {
            criterias.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public static class Criteria{
        private List<Criterion> criteria;

        public Criteria(){
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        private void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        private void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        private void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andIsNull(String property) {
            addCriterion(SimonStringUtil.propertyToField(property) + " is null");
            return this;
        }

        public Criteria andIsNotNull(String property) {
            addCriterion(SimonStringUtil.propertyToField(property) + " is not null");
            return this;
        }

        public Criteria andLike(String property,Object value) {
            addCriterion(SimonStringUtil.propertyToField(property) +" like ", value, property);
            return this;
        }

        public Criteria andEqualTo(String property,Object value) {
            addCriterion(SimonStringUtil.propertyToField(property) +" =", value, property);
            return this;
        }

        public Criteria andNotEqualTo(String property,Object value) {
            addCriterion(SimonStringUtil.propertyToField(property) + " <>", value, property);
            return this;
        }

        public Criteria andGreaterThan(String property,Object value) {
            addCriterion(SimonStringUtil.propertyToField(property) + " >", value, property);
            return this;
        }

        public Criteria andGreaterThanOrEqualTo(String property,Object value) {
            addCriterion(SimonStringUtil.propertyToField(property) + " >=", value, property);
            return this;
        }

        public Criteria andLessThan(String property,Object value) {
            addCriterion(SimonStringUtil.propertyToField(property) + " <", value, property);
            return this;
        }

        public Criteria andLessThanOrEqualTo(String property,Object value) {
            addCriterion(SimonStringUtil.propertyToField(property) + " <=", value, property);
            return this;
        }

        public Criteria andIn(String property,List<Object> values) {
            addCriterion(SimonStringUtil.propertyToField(property) + " in", values, "roleId",property);
            return this;
        }

        public Criteria andNotIn(String property,List<Object> values) {
            addCriterion(SimonStringUtil.propertyToField(property) + " not in", values, property);
            return this;
        }

        public Criteria andBetween(String property,Object value1, Object value2) {
            addCriterion(SimonStringUtil.propertyToField(property) + " between", value1, value2, property);
            return this;
        }

        public Criteria andNotBetween(String property,Object value1, Object value2) {
            addCriterion(SimonStringUtil.propertyToField(property) + " not between", value1, value2, property);
            return this;
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}

7.4 添加上面类用到的工具类

package com.simon.util;

import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;

public class SimonStringUtil {
    /**
     * 对象属性转换为字段  例如:userName to user_name
     * @param property 字段名
     * @return
     */
    public static String propertyToField(String property) {
        if (null == property) {
            return "";
        }
        char[] chars = property.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (char c : chars) {
            if (CharUtils.isAsciiAlphaUpper(c)) {
                sb.append("_" + StringUtils.lowerCase(CharUtils.toString(c)));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }  

    /**
     * 字段转换成对象属性 例如:user_name to userName
     * @param field
     * @return
     */
    public static String fieldToProperty(String field) {
        if (null == field) {
            return "";
        }
        char[] chars = field.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == ‘_‘) {
                int j = i + 1;
                if (j < chars.length) {
                    sb.append(StringUtils.upperCase(CharUtils.toString(chars[j])));
                    i++;
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

7.5 修改实体类方法参数,将Example修改为FilterCondition filterCondition

package com.simon.dao;

import com.simon.model.AreaInfo;
import com.simon.util.FilterCondition;

import java.util.List;

public interface AreaInfoMapper {
    int countByFilterCondition(FilterCondition filterCondition);

    int deleteByFilterCondition(FilterCondition filterCondition);

    int deleteByPrimaryKey(Integer id);

    int insert(AreaInfo record);

    int insertSelective(AreaInfo record);

    List<AreaInfo> selectByFilterCondition(FilterCondition filterCondition);

    AreaInfo selectByPrimaryKey(Integer id);

    int updateByFilterConditionSelective(AreaInfo record, FilterCondition filterCondition);

    int updateByFilterCondition(AreaInfo record, FilterCondition filterCondition);

    int updateByPrimaryKeySelective(AreaInfo record);

    int updateByPrimaryKey(AreaInfo record);
}

全部流程结束,后期需要添加spring,springmvc可以自行完成

时间: 2024-10-19 10:17:34

mybatis-generator在eclipse maven环境下使用的相关文章

在linux+eclipse+maven环境下调试Hbase服务源码,启动Hmaster

由于论文工作,想在regionserver的ipcserver和hregionserver等类进行修改源码的工作. 所以我需要在我的虚拟机中,我的虚拟机环境是32位centos中安装eclipse,调试Hbase的源码. 搭建环境主要步骤基本按照http://www.cnblogs.com/shitouer/archive/2012/10/24/2736923.html来进行.我主要记录下我自己搭建环境遇到的问题. 我的基本步骤, 1,eclipse按照svn插件, 2,通过svn拉去tag中的

mybatis generator在eclipse上的配置与使用(在maven上配置方法)

mybatis generator在eclipse上的配置主要有在以下几个文件上需要进行修改内容:pom.xml,以及配置文件generatorConfig.xml的创建与编写. 1.在pom.xml上添加 在pom.xml上添加以下配置信息: <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId&

Maven环境下多模块项目构建

Maven环境下多模块项目构建 一.新建项目 1.建立我们的父模块par 2.建立我们的子模块dao层 3.建立我们的子模块service层 4.建立我们的子模块web层 5.全部配置完成后,怎么把我们的四个项目关联起来 1)添加一个dao层 2)service里面添加对应的dao依赖 3)然后回到我们的web 4)把这4个项目安装到本地 选择Run 的第二个,然后输入:clean compile install 5)配置一个tomcat插件,为执行做准备

Eclipse开发环境下搭建Maven

(一)开发环境 Eclipse Mars2(4.5.2)  + Maven 3.5.0 (二)配置步骤 1.首先,需要将Maven环境配置好,maven下载地址:http://maven.apache.org/download.cgi 下载完成后,到maven安装目录下的conf文件夹,修改settings.xml文件,在mirrors标签下增加如下内容: 配置maven仓库镜像,可以使以后下载jar包时提升速度 <mirror> <id>alimaven</id> &

Idea中maven环境下搭建MyBatis项目(一)

1.选择Maven框架下的webapp 1.1 添加新节点:archetypeCatalog=internal 1.2 或者在settings------->Build,Execution,Deployment-->Maven-->VM Options设置 -DarchetypeCatalog=internal 2.在Maven的pom文件中引入MyBatis需要用的jar包: 创建对应的java项目,引入需要的mybatis需要的jar,以及连接mysql数据库的jar! asm-3.

eclipse - maven环境搭建

第一步:下载maven 登录maven官网https://maven.apache.org/ 进入下载页面,点击下载 下载完毕后解压,然后放入一个你自定义的目录位置 本人在E盘新建了一个maven目录 配置MAVEN_HOME变量 将加入到path路径下 %MAVEN_HOME%\bin\ cmd窗口验证是否安装成功 输入mvn -v 修改安装目录下的setting.xml这个文件 三.配置Maven本地仓库 1. 在E:\maven目录下新建maven-repository文件夹,该目录用作m

MyBatis Generator For Eclipse 插件安装

由于在ORM框架MyBatis中,实现数据表于JavaBean映射时,配置的代码比较的复杂,所以为了加快开发的效率,MyBatis官方提供了一个Eclipse的插件, 我izuoyongjiushishengchengORM映射所需要的文件.所以下面就教大家怎么在Eclipse上安装这样的一款插件. 在线安装 打开eclipse,点击Help>Software Update 选择 "Available Software" 标签,点击 "Add Site" 按钮

eclipse下安装 maven环境下运行 jetty

转http://www.cnblogs.com/nightswatch/p/4639687.html 一.eclipse中jetty插件安装: 打开eclipse,依次点击菜单Help->Eclipse Marketplace,在Find后面的框中输入jetty,选择第一项进行install即可. 二.jetty插件的使用: POM文件的配置: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&quo

eclipse + maven 环境配置

第一步:准备以下软件并进行安装 1. jdk1.7或者以上为最佳: 官方下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 2. eclipse-jee-mars-2(个人比较倾向 mars 版本的),32位系统准备eclipse-jee-mars-2-win32.zip,64位系统准备eclipse-jee-mars-2-win32-x86_64.zip: 官方下载地址