SpringBoot整合MyBatis

SpringBoot整合MyBatis

SpringBoot和MyBatis可以说是现在最主流的后端框架,是基础中的基础

创建工程

创建Springboot工程,记得勾选 web、web Servic、mybatis、mysql和lombok

pom.xml中应至少有以下依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

同时我最终的目录结构如下:

截屏20200324下午3.11.01.png

构建输入库

其对应的数据库 Schema 脚本如下:

DROP TABLE IF EXISTS user;
 
CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);

其对应的数据库 Data 脚本如下:

DELETE FROM user;
 
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

创建实体类User

使用了lombok插件

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

创建接口UserRepository

添加5个增删该查的方法

public interface UserRepository {

    int save(User user);

    int update(User user);

    int deleteById(long id);

    List<User> findAll();

    User findById(long id);

}

创建接口对应的mapper

创建UserRepository.xml,并编写对应接口的5个方法

<?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.mybatis.repository.UserRepository">
    <insert id="save" parameterType="com.example.mybatis.entity.User">
        INSERT INTO user (id, name, age, email) VALUES (#{id}, #{name}, #{age}, #{email})
    </insert>
    <update id="update" parameterType="com.example.mybatis.entity.User">
        update user set name = #{name},age = #{age},email = #{email} where id = #{id}
    </update>
    <delete id="deleteById" parameterType="long">
        delete from user where id = #{id}
    </delete>
    <select id="findAll" resultType="com.example.mybatis.entity.User">
        select * from user
    </select>
    <select id="findById" parameterType="long" resultType="com.example.mybatis.entity.User">
        select * from user where id = #{id}
    </select>
</mapper>

创建配置文件application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
    username: root
    password: root

mybatis:
  # 指定实体类包路径
  typeAliasesPackage: com.example.mybatis.entity
  # 指定xml文件扫描路径
  mapper-locations: classpath*:mapper/*.xml

SpringBoot启动类

在创建项目自动生成的启动类上添加@MapperScan,其中的值是你接口的路径,如下所示,

@SpringBootApplication
@MapperScan("com.example.mybatis.repository")
public class MybatisApplication {

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

}

编写UserController

注意Controller类的上方要有@RestController注解

@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/findAll")
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @GetMapping("/findAll/{id}")
    public User findById(@PathVariable("id") Long id) {
        return userRepository.findById(id);
    }

    @PostMapping("/save")
    public void save(@RequestBody User user) {
        userRepository.save(user);
    }

    @PutMapping("/update")
    public void update(@RequestBody User user) {
        userRepository.update(user);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Long id) {
        userRepository.deleteById(id);
    }
}

测试

运行启动类,在浏览器或者postman上试试吧

截屏20200324下午3.41.22.png

方法我都实际运行过,没有问题,如果你不会使用save和update方法,可以看下图,这是update方法,需要注意画圈圈的几点地方

截屏20200324下午3.49.27.png

结语

有错误请及时指出