SpringBoot 篇 - 集成MyBatis

作者: 乘风破浪的姐姐 | 来源:发表于2018-12-04 09:50 被阅读16次

    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();
        }
    
    }
    

    相关文章

      网友评论

        本文标题:SpringBoot 篇 - 集成MyBatis

        本文链接:https://www.haomeiwen.com/subject/bffrdftx.html