Spring Boot从入门到精通-集成mybatis

在上一节中我们简单的使用了spring的JdbcTemplate来进行数据库操作,但是在实际的项目中使用mybatis来连接数据库是更好的选择。接下来我们将在项目中集成mybatis。

  1. 首先在pom.xml中加入mybatis的依赖
 <dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>1.3.0</version>
</dependency>
  1. 然后在pom.xml中的build节点下的plugins节点新增一个自动生成代码插件
<plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.3.2</version>
     <configuration>
        <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
          <overwrite>true</overwrite>
          <verbose>true</verbose>
      </configuration>
</plugin>
  1. 接下来在application.yml中新增以下配置,yml文件对格式有要求,冒号后面必须空格,否则会识别不了。有关于yml的具体配置之后会详细讲解。
## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.example.demo.model  # 注意:对应实体类的路径

#pagehelper分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
  1. 在项目路径下新建model文件夹,在其中新建user.java实体类。
package com.example.demo.model;

public class User {
    private Integer userId;

    private String userName;

    private String password;

    private String phone;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }
}

  1. 项目路径下新建mapper文件夹,新建UserMapper.java
package com.example.demo.mapper;

import com.example.demo.model.User;

import java.util.List;

public interface UserMapper {
    int deleteByPrimaryKey(Integer userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    //这个方式我自己加的
    List<User> selectAllUser();
}
  1. 在resources路径下新建mapping文件夹,新建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.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.example.demo.model.User" >
        <id column="user_id" property="userId" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="phone" property="phone" jdbcType="VARCHAR" />
    </resultMap>
    <sql id="Base_Column_List" >
        user_id, user_name, password, phone
    </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from t_user
        where user_id = #{userId,jdbcType=INTEGER}
    </select>
    <!-- 这个方法是我自己加的 -->
    <select id="selectAllUser" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from t_user
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from t_user
        where user_id = #{userId,jdbcType=INTEGER}
    </delete>
    <insert id="insert" parameterType="com.example.demo.model.User" >
        insert into t_user (user_id, user_name, password,
        phone)
        values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
        #{phone,jdbcType=VARCHAR})
    </insert>
    <insert id="insertSelective" parameterType="com.example.demo.model.User" >
        insert into t_user
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="userId != null" >
                user_id,
            </if>
            <if test="userName != null" >
                user_name,
            </if>
            <if test="password != null" >
                password,
            </if>
            <if test="phone != null" >
                phone,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="userId != null" >
                #{userId,jdbcType=INTEGER},
            </if>
            <if test="userName != null" >
                #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="phone != null" >
                #{phone,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.model.User" >
        update t_user
        <set >
            <if test="userName != null" >
                user_name = #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                password = #{password,jdbcType=VARCHAR},
            </if>
            <if test="phone != null" >
                phone = #{phone,jdbcType=VARCHAR},
            </if>
        </set>
        where user_id = #{userId,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.example.demo.model.User" >
        update t_user
        set user_name = #{userName,jdbcType=VARCHAR},
        password = #{password,jdbcType=VARCHAR},
        phone = #{phone,jdbcType=VARCHAR}
        where user_id = #{userId,jdbcType=INTEGER}
    </update>
</mapper>

完成之后项目结构如图:


项目结构
  1. 在service中新增方法testMapper方法并自动注入mapper
package com.example.demo.service;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DemoService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserMapper userMapper;

    public List<Map<String, Object>> test () {
        return jdbcTemplate.queryForList("select * from user");
    }

    public List<User> testMapper () {
        return userMapper.selectAllUser();
    }
}
  1. 在controller中新增另一个接口,调用刚刚在service中新增的方法
@GetMapping("/testMapper")
    public List<User> testMapper() {
        return demoService.testMapper();
    }
  1. 启动项目,在浏览器中调用http://localhost:8080/testMapper,即可得到我们想要的结果。此处步骤较多,如果项目在启动过程中报错的话,请仔细检查yml配置以及xml中的各项语法。
    xml中namespace为对应的mapper实体类,resultMap的type为返回值对应的实体类,各个节点中的parameterType为输入参数对应的实体类,这些路径都要正确。
    以上就是Spring Boot简单的整合mybatis,后期会对这个整合做进一步的深入探究。
    现在我们已经有了两个可以和数据库交流的接口了,在下一节通过Spring Boot与swagger整合来开发一个我们自己的接口文档。Spring Boot从入门到精通-集成swagger
    Spring Boot从入门到精通-mybatis多数据源

您的关注是我最大的动力

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