自学内容网 自学内容网

SpringBoot整合MyBatis记录

整体目录结构

创建数据库

 创建一个MySQL的表,表名是student。

create table student
(
    id   int auto_increment comment '唯一标识id'
        primary key,
    name varchar(30) not null comment '姓名',
    age  int         not null comment '年龄'
)

插入一条数据记录到数据库当中去

insert into student(id,name,age) VALUES(2,'Tom',22)

pom.xml 引入maven依赖

pom.xml中引入springboot和mybatis的一些Maven依赖。

        <dependency>
                <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
            <version>8.0.33</version>
        </dependency>

        <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
  • spring-boot-starter-web: 可以为Web开发提供支持,为我们提供了嵌入的 Servlet 容器以及 Spring MVC 的依赖,并为 Spring MVC 提供了大量自动配置。
  • mysql-connector-java:数据库驱动包。
  • mybatis-spring-boot-starter:连接 Spring Boot 和 MyBatis,构建基于 Spring Boot 的 MyBatis 应用程序。

application.yml 数据源配置

然后application.yml里添加对应的配置

server:
    port: 8081
spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: 123456
        url: jdbc:mysql://127.0.0.1:3306/test
        username: root
    jpa:
        show-sql: true
mybatis:
    type-aliases-package: com.example.springbootdownloader.entity
    mapper-locations: classpath:mapper/*.xml
    configuration:
        map-underscore-to-camel-case: true

application.yml 配置文件中 mybatis 字段中定义的几个属性需要关注一下。

  • mapper-locations:指定 MyBatis 的 XML 映射文件的位置,mapping/*Mapper.xml 表示 MyBatis 会去 resources/mapper 目录下查找所有的 xml 文件,作为映射文件。
  • type-aliases-package:扫描实体类的位置,在此处指明扫描实体类的包,在 mapper.xml 中就可以不写实体类的全路径名。
  • map-underscore-to-camel-case:通常数据库列使用大写字母组成的单词命名,单词间用下划线分隔,而 Java 属性一般遵循驼峰命名法约定。为了在这两种命名方式之间启用自动映射,需要将 mapUnderscoreToCamelCase 设置为 true。

创建实体类

根据我们之前创建的数据库 student 表,在 src/main/java/com/example/springbootdownloader 目录下创建 entity 目录,并在 entity 目录下创建对应的实体类 Student.java,代码如下:

package com.example.springbootdownloader.entity;


import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "student", schema = "test")
public class Student  {
    /**
     * 唯一标识id
     */
    @Id
    private Integer id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getId() {
        return id;
    }

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

创建 mapper 接口

MyBatis 中提供了两种方式来实现 SQL 语句映射,一种是通过 XML 来定义语句,还有一种是通过注解的方式,注解的方式更加简洁、方便,但是不如 XML 来的功能强大、直观,这里由于文章篇幅有限,重点介绍 XML 的形式来实现 SQL 语句映射。

首先定义一个 mapper 接口。

src/main/java/com/example/springbootdownloader 目录下创建 mapper 目录,在 mapper 目录中新建 StudentMapper.java 接口文件,内容如下:

package com.example.springbootdownloader.mapper;

import com.example.springbootdownloader.entity.Student;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentMapper {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    Student queryById(Integer id);

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    List<Student> queryAllByLimit(int offset, int limit);

    /**
     * 新增数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    Student insert(Student student);

    /**
     * 修改数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    Student update(Student student);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    boolean deleteById(Integer id);

}

为了能在 Spring Boot 启动的时候找到我们定义的 mapper 接口文件,还需要在启动类中通过@MapperScan("com.example.springbootdownloader.mapper") 注解指定 mapper 文件的扫描的路径:

package com.example.springbootdownloader;

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

@SpringBootApplication
@MapperScan("com.example.springbootdownloader.mapper")
public class SpringbootDownloaderApplication {

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

}

创建 mapper 的XML

上节中创建的 mapper 接口文件还需要创建一个 mapper XML 文件与之对应,mapper XML 文件中主要定义了 SQL 语句。

在 resources/mapper 目录下创建一个 StudentMapper.xml 文件,由于之前我们在 application.yml 中通过 mapper-locations 属性已经指定了映射文件的查找路径,因此 MyBatis 会自动扫描此指定包的所有 mapper 并创建实现类。

StudentMapper.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.springbootdownloader.mapper.StudentMapper">
    <resultMap type="com.example.springbootdownloader.entity.Student" id="StudentMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
    </resultMap>

    <!--查询单个-->
    <select id="queryById" resultMap="StudentMap">
        select id,
               name,
               age
        from student
        where id = #{id}
    </select>

    <!--查询指定行数据-->
    <select id="queryAllByLimit" resultMap="StudentMap">
        select id,
               name,
               age
        from student limit #{offset}, #{limit}
    </select>

    <!--通过实体作为筛选条件查询-->
    <select id="queryAll" resultMap="StudentMap">
        select
        id, name, age
        from student
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
        </where>
    </select>

    <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into student(name, age)
        values (#{name}, #{age})
    </insert>

    <!--通过主键修改数据-->
    <update id="update">
        update student
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
        </set>
        where id = #{id}
    </update>

    <!--通过主键删除-->
    <delete id="deleteById">
        delete
        from student
        where id = #{id}
    </delete>

</mapper>

在开发 mapper 文件过程中需要注意以下几点:

  • mapper 映射文件的 namespace 必须要和 mapper 接口的完全限定名保持一致。
  • mapper 映射文件中 statement 的 id 必须与 mapper 接口中的方法的方法名保持一致。
  • mapper 映射文件中 statement 的 parameterType 指定的类型必须与 mapper 接口中方法的参数类型保持一致。
  • mapper 映射文件中 statement 的 resultType 指定的类型必须与 mapper 接口中方法的返回值类型保持一致。如果在 application.yml 文件中的 type-aliases-package 指定了扫描实体类的位置,就可以省略类的具体路径而直接写类名。
  • insert 语句中,因为 user 表的 id 是自增的,那么,如果在 SQL 中不传 id,但希望获取插入后的主键,就可以设置 useGeneratedKeys 属性。

MyBatis XML 映射器的具体用法可以参考 MyBatis 文档。

创建 service

在 src/main/java/com/example/springbootdownloader 目录下创建 service 目录,在 service 目录中新建 StudentService.java 文件,内容如下:

package com.example.springbootdownloader.service;

import com.example.springbootdownloader.entity.Student;
import com.example.springbootdownloader.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StudentService {

    @Autowired
    StudentMapper studentMapper;

    public Student queryById(Integer id) {
        return studentMapper.queryById(id);
    }

    public List<Student> queryAllByLimit(int offset, int limit) {
        return studentMapper.queryAllByLimit(offset, limit);
    }

    public Student insert(Student student) {
        return studentMapper.insert(student);
    }

    public Student update(Student student) {
        return studentMapper.update(student);
    }

    public boolean deleteById(Integer id) {
        return studentMapper.deleteById(id);
    }
}

service 中通过 @Autowired 注解注入 studentMapperservice 就可以通过 studentMapper 中定义的数据库方法来访问数据库。

创建 controller

在 src/main/java/com/example/springbootdownloader目录下创建 controller 目录,在 controller 目录中新建 StudentController.java 文件,内容如下:

package com.example.springbootdownloader.controller;


import com.example.springbootdownloader.entity.Student;
import com.example.springbootdownloader.service.StudentService;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("student")
public class StudentController {
    /**
     * 服务对象
     */
    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Student selectOne(@RequestParam Integer id) {
        return this.studentService.queryById(id);
    }

    @GetMapping("test")
    public String test() {
        return "StudentController test";
    }
}

通过 @GetMapping 注解定义了两个 GET 请求,路由 student/selectOne 表示根据id查询某个用户信息,路由 student/test 表示测试一下请求路径是否能访问。

接口测试

运行上述SpringbootDownloaderApplication的main方法,然后用postman接口测试

输入这个接口测试访问

http://localhost:8081/student/selectOne?id=2

返回数据库里前面自己插入数据库的数据的话

{
    "id": 2,
    "name": "Tom",
    "age": 22
}

证明初步完成


 

参考:

Spring Boot整合MyBatis(保姆级教程)_springboot集成mybatis保姆级教程-CSDN博客

SpringBoot系列(五)Mybatis整合完整详细版 - 全栈学习笔记 - 博客园


原文地址:https://blog.csdn.net/qq_41688840/article/details/142793811

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!