一、前言

  • 什么是MyBatis?
    MyBatis是目前Java平台最为流行的ORM框架
    https://baike.baidu.com/item/MyBatis/2824918

  • 本篇开发环境
    1、操作系统: Windows 10 X64
    2、Java SDK: jdk-8u141
    3、Maven:3.5
    4、IDE:IntelliJ IDEA 2017
    5、Spring Boot:1.5.6

本项目构建基于:https://ken.io/note/springboot-course-basic-helloworld

二、Spring Boot整合MyBatis

  • 引入核心依赖
package 说明
mybatis-spring-boot-starter MyBatis核心for Spring Boot
mysql-connector-java 用于连接MySQL

pom.xml文件:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
</parent>

<dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

</dependencies>
  • 配置数据库连接

在配置文件:application.yml中增加以下配置:

#数据库连接配置
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/course?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8
    username: mysql
    password: password

#mybatis配置
mybatis:
  mapper-locations: classpath:conf/mybatis/mapper/*.xml

数据库自行创建MySQL下载地址:https://dev.mysql.com/downloads/

  • Package创建
Package 说明
io.ken.springboot.course.model 用于存放实体
io.ken.springboot.course.dao 用于存放数据访问映射*mapper
  • user表&实体创建

1、user表创建脚本

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `hobby` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、user实体

package io.ken.springboot.course.model;

public class User {

    private int id;

    private String name;

    private int age;

    private String hobby;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
}

getger和setter可以选中类名之后使用快捷键Alt+Insert生成

  • 创建UserMapper,用于跟MyBatis数据操作配置(*mapper.xml)映射
package io.ken.springboot.course.dao;

import io.ken.springboot.course.model.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {

    User queryById(int id);

    List<User> queryAll();

    int add(User user);

    int delById(int id);

    int updateById(User user);
}
  • 创建MyBatis配置

1、创建MyBatis配置文件夹
resources/conf/mybatis/mapper

2、在mapper文件夹下创建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="io.ken.springboot.course.dao.UserMapper">

    <select id="queryById" resultType="io.ken.springboot.course.model.User"
            parameterType="int">
        SELECT *  FROM user WHERE id = #{id}
    </select>

    <select id="queryAll" resultType="io.ken.springboot.course.model.User">
        SELECT * FROM user
    </select>

    <insert id="add" parameterType="io.ken.springboot.course.model.User">
        INSERT INTO user(name,age,hobby) VALUES(#{name},#{age},#{hobby})
    </insert>

    <delete id="delById" parameterType="int">
        DELETE FROM user WHERE id = #{id}
    </delete>

    <update id="updateById" parameterType="io.ken.springboot.course.model.User">
        UPDATE user SET name=#{name},age=#{age},hobby=#{hobby} WHERE id = #{id}
    </update>
</mapper>
  • 创建UserController并提供API
package io.ken.springboot.course.controller;

import io.ken.springboot.course.dao.UserMapper;
import io.ken.springboot.course.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 java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/querybyid")
    @ResponseBody
    User queryById(int id) {
        return userMapper.queryById(id);
    }

    @RequestMapping("/queryall")
    @ResponseBody
    List<User> queryAll() {
        return userMapper.queryAll();
    }

    @RequestMapping("/add")
    @ResponseBody
    String add(User user) {
        return userMapper.add(user) == 1 ? "success" : "failed";
    }

    @RequestMapping("/updatebyid")
    @ResponseBody
    String updateById(User user) {
        return userMapper.updateById(user) == 1 ? "success" : "failed";
    }

    @RequestMapping("/delbyid")
    @ResponseBody
    String delById(int id) {
        return userMapper.delById(id) == 1 ? "success" : "failed";
    }
}
  • API测试
API 示例
添加用户 /user/add?name=tom&age=1&hobby=football
更新用户 /user/updatebyid?name=ken&age=18&hobby=coding&id=1
查询指定用户 /user/querybyid?id=1
查询所有用户 /user/queryall
删除指定用户 /user/delbyid?id=2

本文代码示例:https://github.com/ken-io/springboot-course/tree/master/chapter-02-02