Mybatis 使用mybatis_Generator 生成PO类 、mapper.java 类、Mappering.xml映射文件

mybaits是一个半ORM框架,所以主要工作是书写Mapping的映射文件,但由于手写映射文件容易出错,因而采用能自动生成模型类(po类)、Dao接口(mapper.java接口)、Mapper.xml映射文件

一、建立表结构:

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(33) DEFAULT NULL,
  `sex` char(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `student_index1` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

二 、使用的jar包

mybatis-3.2.3.jar
mybatis-generator-core-1.3.2-javadoc.jar
mybatis-generator-core-1.3.2-sources.jar
mybatis-generator-core-1.3.2.jar
mysql-connector-java-5.1.28-bin.jar
ojdbc14.jar

三、配置generatorConfig.xml文件(其中注意:数据库连接参数、Po类的存放位置、Mapper映射文件和mapper接口的存放位置、配置的表明)

<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>

<!-- 数据库连接的信息 :驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" 
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root" password="xing"> 
</jdbcConnection>

<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>

<!-- targetProject :生成PO类的位置 -->
<javaModelGenerator targetPackage="cn.xing.ssm.domain" 
targetProject=".\src">
<!-- enableSubPackages :是否让schema 最为包的后缀-->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库中返回的值被清理前后的空格 -->
<property name="trimeStrings" value="true"/>
</javaModelGenerator>

<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="cn.xing.ssm.dao.mapper" 
targetProject="./src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>

<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.xing.ssm.dao.mapper" 
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>

<!-- 指定数据库表 -->
<table schema="" tableName="student"></table>
</context>
</generatorConfiguration>

四、编写生成po类、mapper.java 类和mapper.xml映射文件类的java代码

package generatorSqlMap;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlMap {
public void generator() throws Exception{
List<String> warnings=new ArrayList<String>();
boolean overwriter=true;
//指定逆向工程配置文件
File configFile=new File("generatorConfig.xml");
ConfigurationParser config=new ConfigurationParser(warnings);
Configuration configuration=config.parseConfiguration(configFile);
DefaultShellCallback callback=new DefaultShellCallback(overwriter);
MyBatisGenerator myBatisGenerator=new MyBatisGenerator(configuration, callback, warnings);
myBatisGenerator.generate(null);
}

public static void main(String args[]) throws Exception{
GeneratorSqlMap generatorSqlMap=new GeneratorSqlMap();
generatorSqlMap.generator();
}
}

运行结果 

生成的po类

package cn.xing.ssm.domain;
public class Student {
    private Integer id;
        private String name;
   
            private String sex;
   
                    public Integer getId() {
       
                       return id;
    }
   
   public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
   
   public void setSex(String sex) {
        this.sex = sex;
    }
}

生成的mapper.java文件

package cn.xing.ssm.dao.mapper;
import cn.xing.ssm.domain.Student;
import cn.xing.ssm.domain.StudentExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface StudentMapper {
    int countByExample(StudentExample example);
    int deleteByExample(StudentExample example);
 
        int deleteByPrimaryKey(Integer id);
   
        int insert(Student record);
   
         int insertSelective(Student record);
   
         List<Student> selectByExample(StudentExample example);
   
        Student selectByPrimaryKey(Integer id);
   
        int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example);
   
        int updateByExample(@Param("record") Student record, @Param("example") StudentExample example);
   
        int updateByPrimaryKeySelective(Student record);
   
       int updateByPrimaryKey(Student record);
   }

生成的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="cn.xing.ssm.dao.mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="cn.xing.ssm.domain.Student" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="CHAR" />
  </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, name, sex
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="cn.xing.ssm.domain.StudentExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from student
    <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" >
    select 
    <include refid="Base_Column_List" />
    from student
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from student
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="cn.xing.ssm.domain.StudentExample" >
    delete from student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="cn.xing.ssm.domain.Student" >
    insert into student (id, name, sex)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=CHAR})
  </insert>
  <insert id="insertSelective" parameterType="cn.xing.ssm.domain.Student" >
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="sex != null" >
        sex,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=CHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="cn.xing.ssm.domain.StudentExample" resultType="java.lang.Integer" >
    select count(*) from student
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update student
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.name != null" >
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.sex != null" >
        sex = #{record.sex,jdbcType=CHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update student
    set id = #{record.id,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      sex = #{record.sex,jdbcType=CHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="cn.xing.ssm.domain.Student" >
    update student
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        sex = #{sex,jdbcType=CHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="cn.xing.ssm.domain.Student" >
    update student
    set name = #{name,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=CHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

你可能感兴趣的:(Mybatis 使用mybatis_Generator 生成PO类 、mapper.java 类、Mappering.xml映射文件)