Mybatis自动生成代码

时间:2022-12-05 09:09:38

         林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

       摘要:本文将简要介绍怎样利用Mybatis Generator自动生成Mybatis的相关代码,Mybatis Generator是一个非常好用的工具,使用它可以大大节省开发的时间,并减少代码的编写量。

本文工程免费下载

一、构建一个环境


1. 首先创建一个表:

CREATE TABLE    t_user
(
USER_ID INT NOT NULL AUTO_INCREMENT,
USER_NAME CHAR(30) NOT NULL,
USER_PASSWORD CHAR(10) NOT NULL,
USER_EMAIL CHAR(30) NOT NULL,
PRIMARY KEY (USER_ID)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. 在 Mybatis 主页 http://code.google.com/p/mybatis/ 上下载 Mybatis mybatis-generator-core 或者在这里下载:http://download.csdn.net/detail/evankaka/8926999

二、xml文件编写

1、新建一个工程。然后新建如下包,都是空的

Mybatis自动生成代码

2、然后新建generator.xmll文件

内容如下:

<?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:数据库的JDBC驱动的jar包地址 -->	<classPathEntry location="D:\Java\Jar\mysql-connector-java-5.1.22\mysql-connector-java-5.1.22-bin.jar" />	<context id="DB2Tables" targetRuntime="MyBatis3">		<commentGenerator>		<!-- 抑制警告 -->		<property name="suppressTypeWarnings" value="true" />		<!-- 是否去除自动生成的注释 true:是 : false:否 -->		<property name="suppressAllComments" value="false" />		<!-- 是否生成注释代时间戳-->  		<property name="suppressDate" value="true" /> 		</commentGenerator>		<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->		<jdbcConnection driverClass="com.mysql.jdbc.Driver"			connectionURL="jdbc:mysql://localhost/learning" userId="root"			password="christmas258@">		</jdbcConnection>		<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 			NUMERIC 类型解析为java.math.BigDecimal -->	<!-- 	<javaTypeResolver>			<property name="forceBigDecimals" value="false" />		</javaTypeResolver> -->        <!--生成Model类存放位置 -->		<javaModelGenerator targetPackage="com.lin.domain"			targetProject="D:\lunaJee-workspace\MyBatisLearningChapter7\src">			 <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->  			<property name="enableSubPackages" value="false" />			 <!-- 是否针对string类型的字段在set的时候进行trim调用 -->  			<property name="trimStrings" value="true" />		</javaModelGenerator>        <!--生成映射文件存放位置 -->		<sqlMapGenerator targetPackage="com.lin.mapper"			targetProject="D:\lunaJee-workspace\MyBatisLearningChapter7\src">			<property name="enableSubPackages" value="true" />		</sqlMapGenerator>        <!--生成Dao类存放位置 -->		<javaClientGenerator type="XMLMAPPER"			targetPackage="com.lin.dao" targetProject="D:\lunaJee-workspace\MyBatisLearningChapter7\src">			<property name="enableSubPackages" value="true" />		</javaClientGenerator>		       	<!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->          <table schema="general" tableName="T_USER" domainObjectName="User">         <!--domain字段的命名规则,false:默认为驼峰命名 true:按数据库真实命名  -->        <property name="useActualColumnNames" value="false"/>        <!-- 忽略列,不生成bean 字段 -->          <!--     <ignoreColumn column="FRED" />   -->        <!-- 指定列的java数据类型 -->          <!--     <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />   -->        </table>	</context></generatorConfiguration>

三、自动代码生成

自动代码生成有4种方法

1、直接cmd下命令行生成

命令如下:java -jar 电脑上mybatis-generator-core-1.3.0.jar的绝对路径  -configfile 电脑上generator.xml的绝对路径,这里的generator.xml不一定要放在工程的src文件中。

如我的这个项目就是:

Mybatis自动生成代码

运行的结果如下:

Mybatis自动生成代码

然后在eclipse中刷新一下:结果出来了

Mybatis自动生成代码

看看各个文件

(1)User.java

package com.lin.domain;public class User {    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database column t_user.USER_ID     *     * @mbggenerated     */    private Integer userId;    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database column t_user.USER_NAME     *     * @mbggenerated     */    private String userName;    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database column t_user.USER_PASSWORD     *     * @mbggenerated     */    private String userPassword;    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database column t_user.USER_EMAIL     *     * @mbggenerated     */    private String userEmail;    /**     * This method was generated by MyBatis Generator.     * This method returns the value of the database column t_user.USER_ID     *     * @return the value of t_user.USER_ID     *     * @mbggenerated     */    public Integer getUserId() {        return userId;    }    /**     * This method was generated by MyBatis Generator.     * This method sets the value of the database column t_user.USER_ID     *     * @param userId the value for t_user.USER_ID     *     * @mbggenerated     */    public void setUserId(Integer userId) {        this.userId = userId;    }    /**     * This method was generated by MyBatis Generator.     * This method returns the value of the database column t_user.USER_NAME     *     * @return the value of t_user.USER_NAME     *     * @mbggenerated     */    public String getUserName() {        return userName;    }    /**     * This method was generated by MyBatis Generator.     * This method sets the value of the database column t_user.USER_NAME     *     * @param userName the value for t_user.USER_NAME     *     * @mbggenerated     */    public void setUserName(String userName) {        this.userName = userName == null ? null : userName.trim();    }    /**     * This method was generated by MyBatis Generator.     * This method returns the value of the database column t_user.USER_PASSWORD     *     * @return the value of t_user.USER_PASSWORD     *     * @mbggenerated     */    public String getUserPassword() {        return userPassword;    }    /**     * This method was generated by MyBatis Generator.     * This method sets the value of the database column t_user.USER_PASSWORD     *     * @param userPassword the value for t_user.USER_PASSWORD     *     * @mbggenerated     */    public void setUserPassword(String userPassword) {        this.userPassword = userPassword == null ? null : userPassword.trim();    }    /**     * This method was generated by MyBatis Generator.     * This method returns the value of the database column t_user.USER_EMAIL     *     * @return the value of t_user.USER_EMAIL     *     * @mbggenerated     */    public String getUserEmail() {        return userEmail;    }    /**     * This method was generated by MyBatis Generator.     * This method sets the value of the database column t_user.USER_EMAIL     *     * @param userEmail the value for t_user.USER_EMAIL     *     * @mbggenerated     */    public void setUserEmail(String userEmail) {        this.userEmail = userEmail == null ? null : userEmail.trim();    }}

UserExample.java这个文件可以控制是否生成

package com.lin.domain;import java.util.ArrayList;import java.util.List;public class UserExample {    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database table t_user     *     * @mbggenerated     */    protected String orderByClause;    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database table t_user     *     * @mbggenerated     */    protected boolean distinct;    /**     * This field was generated by MyBatis Generator.     * This field corresponds to the database table t_user     *     * @mbggenerated     */    protected List<Criteria> oredCriteria;    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public UserExample() {        oredCriteria = new ArrayList<Criteria>();    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public void setOrderByClause(String orderByClause) {        this.orderByClause = orderByClause;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public String getOrderByClause() {        return orderByClause;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public void setDistinct(boolean distinct) {        this.distinct = distinct;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public boolean isDistinct() {        return distinct;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public List<Criteria> getOredCriteria() {        return oredCriteria;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public void or(Criteria criteria) {        oredCriteria.add(criteria);    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public Criteria or() {        Criteria criteria = createCriteriaInternal();        oredCriteria.add(criteria);        return criteria;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public Criteria createCriteria() {        Criteria criteria = createCriteriaInternal();        if (oredCriteria.size() == 0) {            oredCriteria.add(criteria);        }        return criteria;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    protected Criteria createCriteriaInternal() {        Criteria criteria = new Criteria();        return criteria;    }    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    public void clear() {        oredCriteria.clear();        orderByClause = null;        distinct = false;    }    /**     * This class was generated by MyBatis Generator.     * This class corresponds to the database table t_user     *     * @mbggenerated     */    protected abstract static class GeneratedCriteria {        protected List<Criterion> criteria;        protected GeneratedCriteria() {            super();            criteria = new ArrayList<Criterion>();        }        public boolean isValid() {            return criteria.size() > 0;        }        public List<Criterion> getCriteria() {            return criteria;        }        protected void addCriterion(String condition) {            if (condition == null) {                throw new RuntimeException("Value for condition cannot be null");            }            criteria.add(new Criterion(condition));        }        protected 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));        }        protected 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 andUserIdIsNull() {            addCriterion("USER_ID is null");            return (Criteria) this;        }        public Criteria andUserIdIsNotNull() {            addCriterion("USER_ID is not null");            return (Criteria) this;        }        public Criteria andUserIdEqualTo(Integer value) {            addCriterion("USER_ID =", value, "userId");            return (Criteria) this;        }        public Criteria andUserIdNotEqualTo(Integer value) {            addCriterion("USER_ID <>", value, "userId");            return (Criteria) this;        }        public Criteria andUserIdGreaterThan(Integer value) {            addCriterion("USER_ID >", value, "userId");            return (Criteria) this;        }        public Criteria andUserIdGreaterThanOrEqualTo(Integer value) {            addCriterion("USER_ID >=", value, "userId");            return (Criteria) this;        }        public Criteria andUserIdLessThan(Integer value) {            addCriterion("USER_ID <", value, "userId");            return (Criteria) this;        }        public Criteria andUserIdLessThanOrEqualTo(Integer value) {            addCriterion("USER_ID <=", value, "userId");            return (Criteria) this;        }        public Criteria andUserIdIn(List<Integer> values) {            addCriterion("USER_ID in", values, "userId");            return (Criteria) this;        }        public Criteria andUserIdNotIn(List<Integer> values) {            addCriterion("USER_ID not in", values, "userId");            return (Criteria) this;        }        public Criteria andUserIdBetween(Integer value1, Integer value2) {            addCriterion("USER_ID between", value1, value2, "userId");            return (Criteria) this;        }        public Criteria andUserIdNotBetween(Integer value1, Integer value2) {            addCriterion("USER_ID not between", value1, value2, "userId");            return (Criteria) this;        }        public Criteria andUserNameIsNull() {            addCriterion("USER_NAME is null");            return (Criteria) this;        }        public Criteria andUserNameIsNotNull() {            addCriterion("USER_NAME is not null");            return (Criteria) this;        }        public Criteria andUserNameEqualTo(String value) {            addCriterion("USER_NAME =", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameNotEqualTo(String value) {            addCriterion("USER_NAME <>", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameGreaterThan(String value) {            addCriterion("USER_NAME >", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameGreaterThanOrEqualTo(String value) {            addCriterion("USER_NAME >=", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameLessThan(String value) {            addCriterion("USER_NAME <", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameLessThanOrEqualTo(String value) {            addCriterion("USER_NAME <=", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameLike(String value) {            addCriterion("USER_NAME like", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameNotLike(String value) {            addCriterion("USER_NAME not like", value, "userName");            return (Criteria) this;        }        public Criteria andUserNameIn(List<String> values) {            addCriterion("USER_NAME in", values, "userName");            return (Criteria) this;        }        public Criteria andUserNameNotIn(List<String> values) {            addCriterion("USER_NAME not in", values, "userName");            return (Criteria) this;        }        public Criteria andUserNameBetween(String value1, String value2) {            addCriterion("USER_NAME between", value1, value2, "userName");            return (Criteria) this;        }        public Criteria andUserNameNotBetween(String value1, String value2) {            addCriterion("USER_NAME not between", value1, value2, "userName");            return (Criteria) this;        }        public Criteria andUserPasswordIsNull() {            addCriterion("USER_PASSWORD is null");            return (Criteria) this;        }        public Criteria andUserPasswordIsNotNull() {            addCriterion("USER_PASSWORD is not null");            return (Criteria) this;        }        public Criteria andUserPasswordEqualTo(String value) {            addCriterion("USER_PASSWORD =", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordNotEqualTo(String value) {            addCriterion("USER_PASSWORD <>", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordGreaterThan(String value) {            addCriterion("USER_PASSWORD >", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordGreaterThanOrEqualTo(String value) {            addCriterion("USER_PASSWORD >=", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordLessThan(String value) {            addCriterion("USER_PASSWORD <", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordLessThanOrEqualTo(String value) {            addCriterion("USER_PASSWORD <=", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordLike(String value) {            addCriterion("USER_PASSWORD like", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordNotLike(String value) {            addCriterion("USER_PASSWORD not like", value, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordIn(List<String> values) {            addCriterion("USER_PASSWORD in", values, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordNotIn(List<String> values) {            addCriterion("USER_PASSWORD not in", values, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordBetween(String value1, String value2) {            addCriterion("USER_PASSWORD between", value1, value2, "userPassword");            return (Criteria) this;        }        public Criteria andUserPasswordNotBetween(String value1, String value2) {            addCriterion("USER_PASSWORD not between", value1, value2, "userPassword");            return (Criteria) this;        }        public Criteria andUserEmailIsNull() {            addCriterion("USER_EMAIL is null");            return (Criteria) this;        }        public Criteria andUserEmailIsNotNull() {            addCriterion("USER_EMAIL is not null");            return (Criteria) this;        }        public Criteria andUserEmailEqualTo(String value) {            addCriterion("USER_EMAIL =", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailNotEqualTo(String value) {            addCriterion("USER_EMAIL <>", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailGreaterThan(String value) {            addCriterion("USER_EMAIL >", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailGreaterThanOrEqualTo(String value) {            addCriterion("USER_EMAIL >=", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailLessThan(String value) {            addCriterion("USER_EMAIL <", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailLessThanOrEqualTo(String value) {            addCriterion("USER_EMAIL <=", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailLike(String value) {            addCriterion("USER_EMAIL like", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailNotLike(String value) {            addCriterion("USER_EMAIL not like", value, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailIn(List<String> values) {            addCriterion("USER_EMAIL in", values, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailNotIn(List<String> values) {            addCriterion("USER_EMAIL not in", values, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailBetween(String value1, String value2) {            addCriterion("USER_EMAIL between", value1, value2, "userEmail");            return (Criteria) this;        }        public Criteria andUserEmailNotBetween(String value1, String value2) {            addCriterion("USER_EMAIL not between", value1, value2, "userEmail");            return (Criteria) this;        }    }    /**     * This class was generated by MyBatis Generator.     * This class corresponds to the database table t_user     *     * @mbggenerated do_not_delete_during_merge     */    public static class Criteria extends GeneratedCriteria {        protected Criteria() {            super();        }    }    /**     * This class was generated by MyBatis Generator.     * This class corresponds to the database table t_user     *     * @mbggenerated     */    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;        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;        }        protected Criterion(String condition) {            super();            this.condition = condition;            this.noValue = true;        }        protected Criterion(String condition, Object value) {            super();            this.condition = condition;            this.value = value;            if (value instanceof List<?>) {                this.listValue = true;            } else {                this.singleValue = true;            }        }        protected Criterion(String condition, Object value, Object secondValue) {            super();            this.condition = condition;            this.value = value;            this.secondValue = secondValue;            this.betweenValue = true;        }    }}
(2)dao层文件。它自动取名为UserMapper.java,可以自己手动写成UserDao.java

package com.lin.dao;import com.lin.domain.User;import com.lin.domain.UserExample;import java.util.List;import org.apache.ibatis.annotations.Param;public interface UserMapper {    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int countByExample(UserExample example);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int deleteByExample(UserExample example);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int deleteByPrimaryKey(Integer userId);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int insert(User record);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int insertSelective(User record);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    List<User> selectByExample(UserExample example);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    User selectByPrimaryKey(Integer userId);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int updateByExample(@Param("record") User record, @Param("example") UserExample example);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int updateByPrimaryKeySelective(User record);    /**     * This method was generated by MyBatis Generator.     * This method corresponds to the database table t_user     *     * @mbggenerated     */    int updateByPrimaryKey(User record);}

(3)Mapper.xml文件:

<?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.lin.dao.UserMapper" >  <resultMap id="BaseResultMap" type="com.lin.domain.User" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    <id column="USER_ID" property="userId" jdbcType="INTEGER" />    <result column="USER_NAME" property="userName" jdbcType="CHAR" />    <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />    <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />  </resultMap>  <sql id="Example_Where_Clause" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    <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" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    <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" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL  </sql>  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.lin.domain.UserExample" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    select    <if test="distinct" >      distinct    </if>    <include refid="Base_Column_List" />    from t_user    <if test="_parameter != null" >      <include refid="Example_Where_Clause" />    </if>    <if test="orderByClause != null" >      order by ${orderByClause}    </if>  </select>  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    select     <include refid="Base_Column_List" />    from t_user    where USER_ID = #{userId,jdbcType=INTEGER}  </select>  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    delete from t_user    where USER_ID = #{userId,jdbcType=INTEGER}  </delete>  <delete id="deleteByExample" parameterType="com.lin.domain.UserExample" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    delete from t_user    <if test="_parameter != null" >      <include refid="Example_Where_Clause" />    </if>  </delete>  <insert id="insert" parameterType="com.lin.domain.User" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    insert into t_user (USER_ID, USER_NAME, USER_PASSWORD,       USER_EMAIL)    values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=CHAR}, #{userPassword,jdbcType=CHAR},       #{userEmail,jdbcType=CHAR})  </insert>  <insert id="insertSelective" parameterType="com.lin.domain.User" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    insert into t_user    <trim prefix="(" suffix=")" suffixOverrides="," >      <if test="userId != null" >        USER_ID,      </if>      <if test="userName != null" >        USER_NAME,      </if>      <if test="userPassword != null" >        USER_PASSWORD,      </if>      <if test="userEmail != null" >        USER_EMAIL,      </if>    </trim>    <trim prefix="values (" suffix=")" suffixOverrides="," >      <if test="userId != null" >        #{userId,jdbcType=INTEGER},      </if>      <if test="userName != null" >        #{userName,jdbcType=CHAR},      </if>      <if test="userPassword != null" >        #{userPassword,jdbcType=CHAR},      </if>      <if test="userEmail != null" >        #{userEmail,jdbcType=CHAR},      </if>    </trim>  </insert>  <select id="countByExample" parameterType="com.lin.domain.UserExample" resultType="java.lang.Integer" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    select count(*) from t_user    <if test="_parameter != null" >      <include refid="Example_Where_Clause" />    </if>  </select>  <update id="updateByExampleSelective" parameterType="map" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    update t_user    <set >      <if test="record.userId != null" >        USER_ID = #{record.userId,jdbcType=INTEGER},      </if>      <if test="record.userName != null" >        USER_NAME = #{record.userName,jdbcType=CHAR},      </if>      <if test="record.userPassword != null" >        USER_PASSWORD = #{record.userPassword,jdbcType=CHAR},      </if>      <if test="record.userEmail != null" >        USER_EMAIL = #{record.userEmail,jdbcType=CHAR},      </if>    </set>    <if test="_parameter != null" >      <include refid="Update_By_Example_Where_Clause" />    </if>  </update>  <update id="updateByExample" parameterType="map" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    update t_user    set USER_ID = #{record.userId,jdbcType=INTEGER},      USER_NAME = #{record.userName,jdbcType=CHAR},      USER_PASSWORD = #{record.userPassword,jdbcType=CHAR},      USER_EMAIL = #{record.userEmail,jdbcType=CHAR}    <if test="_parameter != null" >      <include refid="Update_By_Example_Where_Clause" />    </if>  </update>  <update id="updateByPrimaryKeySelective" parameterType="com.lin.domain.User" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    update t_user    <set >      <if test="userName != null" >        USER_NAME = #{userName,jdbcType=CHAR},      </if>      <if test="userPassword != null" >        USER_PASSWORD = #{userPassword,jdbcType=CHAR},      </if>      <if test="userEmail != null" >        USER_EMAIL = #{userEmail,jdbcType=CHAR},      </if>    </set>    where USER_ID = #{userId,jdbcType=INTEGER}  </update>  <update id="updateByPrimaryKey" parameterType="com.lin.domain.User" >    <!--      WARNING - @mbggenerated      This element is automatically generated by MyBatis Generator, do not modify.    -->    update t_user    set USER_NAME = #{userName,jdbcType=CHAR},      USER_PASSWORD = #{userPassword,jdbcType=CHAR},      USER_EMAIL = #{userEmail,jdbcType=CHAR}    where USER_ID = #{userId,jdbcType=INTEGER}  </update></mapper>

这样就好了,serivce层的文件自己再去写写就好了。

如果不想要UserExample文件怎么办呢?

那就把

        <table schema="general" tableName="T_USER" domainObjectName="User">         <!--domain字段的命名规则,false:默认为驼峰命名 true:按数据库真实命名  -->        <property name="useActualColumnNames" value="false"/>        </table>
换成:

        <table schema="general" tableName="T_USER" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false"               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">         <!--domain字段的命名规则,false:默认为驼峰命名 true:按数据库真实命名  -->        <property name="useActualColumnNames" value="false"/>        </table>
这样就可以了
2、java代码读取xml文件生成

首先要导入如下的包:

Mybatis自动生成代码

然后在工程里写一个文件如下:

package Test;import java.io.File;import java.io.IOException;import java.sql.SQLException;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.exception.InvalidConfigurationException;import org.mybatis.generator.exception.XMLParserException;import org.mybatis.generator.internal.DefaultShellCallback;public class BuildFile {	public static void main(String[] args) throws InvalidConfigurationException, IOException, XMLParserException, SQLException, InterruptedException {	    List<String> warnings = new ArrayList<String>();  	      boolean overwrite = true;  	      File configFile = new File("D:\\lunaJee-workspace\\MyBatisLearningChapter7\\src\\generator.xml");  //输入绝对路径	      ConfigurationParser cp = new ConfigurationParser(warnings);  	      Configuration config=null;		  config = cp.parseConfiguration(configFile);	      DefaultShellCallback callback = new DefaultShellCallback(overwrite);  	      MyBatisGenerator myBatisGenerator = null;	      myBatisGenerator = new MyBatisGenerator(config, callback, warnings);	      myBatisGenerator.generate(null);	}}

然后运行,再刷新下就可以了

Mybatis自动生成代码

这里说一下,generator.xml文件也是可以随便放的,我这里为了方便,把它和整个工程放在一起了

本文工程免费下载

3、eclipse插入mybatis generator生成

待续~~

4、maven生成

待续~~