Spring Boot整合MyBatis

最近刚做完jpa的测试,因为jpa跟hibernate关联的比较紧密,mybatis由于其灵活的sql配置,深得人心,所以我研究了一下spring boot怎么和mybatis整合,现在写一篇文章来记录所学,不得不说,spring boot真是太强大了,整合起来也非常简单,talk is cheap, show me the code!!

1.引入mybatis

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xuzhang</groupId>
    <artifactId>spring-boot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <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>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.由于我用的是h2来进行测试,所以我需要创建sql文件来初始化表

init.sql

CREATE TABLE IF NOT EXISTS `user` (
    `id`         INTEGER  PRIMARY KEY AUTO_INCREMENT,
     `name` VARCHAR(50) NOT NULL,
     `pwd`        varchar(50) not null
);

application.properties

初始化数据表用的
spring.datasource.schema=classpath:init.sql

3.在启动类添加注解(@MapperScan)指明你要扫描的包。

package com.xuzhang.springbootmybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.xuzhang.springbootmybatis.mappper")
public class SpringBootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatisApplication.class, args);
    }

}

4.创建实体

package com.xuzhang.springbootmybatis.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

5.创建mapper

package com.xuzhang.springbootmybatis.mappper;

import com.xuzhang.springbootmybatis.model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Select("select * from user")
    List<User> findAllUser();

    @Insert("insert into user(name,pwd) values(#{name},#{pwd})")
    void insertUser(@Param("name") String name, @Param("pwd") String pwd);

    @Delete("delete from user where id = #{id}")
    void deleteUser(@Param("id") int id);
}

6.创建controller来进行测试

package com.xuzhang.springbootmybatis.controller;

import com.xuzhang.springbootmybatis.mappper.UserMapper;
import com.xuzhang.springbootmybatis.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("user/findAllUser")
    public List<User> findALlUser() {
        return userMapper.findAllUser();
    }

    @PostMapping("user/insertUser")
    public void insertUser(@RequestBody User user) {
        userMapper.insertUser(user.getName(), user.getPwd());
    }

    @PostMapping("user/deleteUser")
    public void deleteUser(@RequestParam(value = "id") int id) {
        userMapper.deleteUser(id);
    }
}

7.测试结果

  • 添加用户


    addUser
  • 查找用户


    findUser
  • 删除用户


    deleteUser

git:https://gitee.com/xuzhangRIchard/spring-boot-mybatis

推荐阅读更多精彩内容