SpringBoot 篇 - 结合mybatis-generator-maven-plugin插件生成MyBatis代码

1、在pom.xml文件中增加MyBatis的依赖

<!--用于支持mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

2、创建myuser表,使用mysql数据库

CREATE TABLE myuser (
userId int(11) NOT NULL AUTO_INCREMENT,
address varchar(200) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
passWd varchar(20) NOT NULL,
phone varchar(20) DEFAULT NULL,
type int(11) NOT NULL,
userName varchar(20) NOT NULL,
PRIMARY KEY (userId)
) ENGINE=InnoDB AUTO_INCREMENT=97 DEFAULT CHARSET=utf8;

3、在application.propertise文件中添加mybatis配置、数据库配置

spring.datasource.url=jdbc\:mysql\://59.110.139.20\:3306/Interfaces?characterEncoding=utf-8
spring.datasource.username=zhangsan
spring.datasource.password=123123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

driverPath=D:\\repository\\mysql\\mysql-connector-java\\5.1.46\\mysql-connector-java-5.1.46.jar
target_package=com.sc.springmvc

mybatis.mapper-locations=classpath:com/sc/springmvc/mapping/*.xml
mybatis.type-aliases-package=com.sc.springmvc.model

4、结合mybatis-generator-maven-plugin插件自动生成MyBatis代码。
在main/resources目录下新增 generatorConfig.xml文件。详细操作请参考Spring集成MyBatis进行单元测试
generatorConfig.xml文件内容:

<?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="application.properties" />
    <!-- 指定数据连接驱动jar地址 -->
    <classPathEntry location="${driverPath}" />
    <context id="context" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
        <!--<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">-->
            <!--<property name="searchString" value="Example$" />-->
            <!--<property name="replaceString" value="Criteria" />-->
        <!--</plugin>-->
        <!-- 去掉生成出来的代码的注解 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
            <property name="suppressDate" value="true" />
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="${spring.datasource.driver-class-name}"
           connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="${target_package}.model"
                            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置 -->
        <sqlMapGenerator targetPackage="${target_package}.mapping"
                         targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="${target_package}.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--<table tableName="myuser" domainObjectName="User"></table>-->
        <table tableName="myuser" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <property name="useActualColumnNames" value="false" />
        </table>
    </context>
</generatorConfiguration>

自动生成的UserMapper.java:

package com.example.demo.dao;

import com.example.demo.model.User;
import java.math.BigDecimal;

public interface UserMapper {
    int deleteByPrimaryKey(BigDecimal id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(BigDecimal id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

自动生成的UserMapper.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.example.demo.dao.UserMapper">
  <resultMap id="BaseResultMap" type="com.example.demo.model.User">
    <id column="ID" jdbcType="DECIMAL" property="id" />
    <result column="USERNAME" jdbcType="VARCHAR" property="username" />
    <result column="PASSWORD" jdbcType="VARCHAR" property="password" />
  </resultMap>
  <sql id="Base_Column_List">
    ID, USERNAME, PASSWORD
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.math.BigDecimal" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from MYUSER
    where ID = #{id,jdbcType=DECIMAL}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.math.BigDecimal">
    delete from MYUSER
    where ID = #{id,jdbcType=DECIMAL}
  </delete>
  <insert id="insert" parameterType="com.example.demo.model.User">
    insert into MYUSER (ID, USERNAME, PASSWORD
      )
    values (#{id,jdbcType=DECIMAL}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.example.demo.model.User">
    insert into MYUSER
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        ID,
      </if>
      <if test="username != null">
        USERNAME,
      </if>
      <if test="password != null">
        PASSWORD,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=DECIMAL},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.model.User">
    update MYUSER
    <set>
      <if test="username != null">
        USERNAME = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        PASSWORD = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where ID = #{id,jdbcType=DECIMAL}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.demo.model.User">
    update MYUSER
    set USERNAME = #{username,jdbcType=VARCHAR},
      PASSWORD = #{password,jdbcType=VARCHAR}
    where ID = #{id,jdbcType=DECIMAL}
  </update>
</mapper>

自动生成的User.java内容如下:

package com.example.demo.model;
import java.io.Serializable;
import java.math.BigDecimal;

public class User implements Serializable {
    private BigDecimal id;
    private String username;
    private String password;
    private static final long serialVersionUID = 1L;
    public BigDecimal getId() {
        return id;
    }

    public void setId(BigDecimal id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        User other = (User) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
            && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
        result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode());
        return result;
    }
}

5、OK,准备工作都已就绪,开始测试,在controller包下新增UserController类

package com.example.demo.controller;

import com.example.demo.dao.UserMapper;
import com.example.demo.impl.UserServiceImpl;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * Created by Suncy on 2018/5/13 0013.
 */
@Controller
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserServiceImpl userDao;

    @ResponseBody
    @RequestMapping("/find/mybatis/id")
    public String findMailByToFromMybatis(HttpServletRequest request, BigDecimal id) {
       // User userMo = userMapper.selectByPrimaryKey(id);
        User userMo1 = userDao.selectByPrimaryKey(id);
        return  userDao.selectByPrimaryKey(id).toString();
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,367评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,959评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,750评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,226评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,252评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,975评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,592评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,497评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,027评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,147评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,274评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,953评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,623评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,143评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,260评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,607评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,271评论 2 358