使用MyBatis框架操作数据,在SpringBoot框架中集成MyBatis。 使用步骤如下:

1、准备好数据库
?serverTimezone=GMT

在SpringBoot框架中集成MyBatis_spring

在SpringBoot框架中集成MyBatis_java_02

2、MyBatis起步依赖:完成MyBatis对象自动配置,对象放在容器中

创建模块的时候,需要勾选spring web、MyBatis Framework、MySQL Driver 这三个

在SpringBoot框架中集成MyBatis_java_03

pom.xml文件

<?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 https://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.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cqjtu</groupId>
    <artifactId>springbootsql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--web的起步依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis的起步依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- mysql驱动-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--测试要用到的-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <!--resource插件,这个在创建好项目后要手动添加 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.xml</include> <!--代表所有目录下的.xml文件 -->
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
3、创建实体类Student

对应数据库中的每一个

package com.cqjtu.model;

public class Student
{
    // 所有属性名必须和数据库中的命名一样
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId()
    {
        return id;
    }

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

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

    @Override
    public String toString()
    {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
4、创建Dao接口StudentDao,创建一个查询学生的方法
package com.cqjtu.dao;

import com.cqjtu.model.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

//@Mapper // 告诉mybatis这是dao接口,创建此接口的代理对象,这里不用这种方式
public interface StudentDao
{
    // Param注解就是给SQL语句中的参数赋值
    // 当外部要获取传给 id 的值时,只需要写 studId
    Student selectById(@Param("stuId")Integer id);
}
5、创建Dao接口对应的Mapper文件即.xml文件,用来写SQL语句

文件应该在同一个包下,且文件名应该一致

在SpringBoot框架中集成MyBatis_java_04

<?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">
<!--上面这些应该是固定的 -->    
<!--namespace是StudentDao两个文件所在的位置 -->   
<mapper namespace="com.cqjtu.dao.StudentDao">
<!--下面是SQL语句,id要和接口StudentDao中的查询方法名字一致 -->
<!--resultType是查询的返回结果类型,即Student类对象,要把他的位置写全 -->
<!--stuId就是@Param注解里的 -->
    <select id="selectById" resultType="com.cqjtu.model.Student">
        select id,name,age from student where id=#{stuId}
    </select>
</mapper>
6、创建Service层对象,创建StudentService接口和它的实现类StudentServiceImpl

在SpringBoot框架中集成MyBatis_java_05

接口

package com.cqjtu.service;

import com.cqjtu.model.Student;

public interface StudentService
{
    Student queryStudent(Integer id);
}

实现类

package com.cqjtu.service.impl;

import com.cqjtu.dao.StudentDao;
import com.cqjtu.service.StudentService;
import org.springframework.stereotype.Service;
import com.cqjtu.model.Student;

import javax.annotation.Resource;

@Service 
public class StudentServiceImpl implements StudentService
{
    @Resource // 自动注入
    private StudentDao studentDao;
    
    @Override
    public Student queryStudent(Integer id)
    {
        return studentDao.selectById(id); // 调用查询方法
    }
}
7、创建Controller对象,访问Service
package com.cqjtu.controller;

import com.cqjtu.model.Student;
import com.cqjtu.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
public class StudentController
{
    @Resource
    private StudentService studentService;
    
    @RequestMapping("/student/query")
    @ResponseBody
    public String queryStudent(Integer id)
    {
        Student student = studentService.queryStudent(id);
        return student.toString();
    }
}
8、在application.yml文件中配置数据库的连接信息
// 配置端口号
server:
  port: 9001
  servlet:
    context-path: /orm

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver // 驱动
    url: jdbc:mysql://localhost:3306/springdb   //最后的springdb是要连接的数据库名
    username: root //账号、密码别搞错了
    password: 123456
9、测试

注意MapperScan注解如果有多个Dao,就要重复写Mapper注解,而在Application类上面写一个MapperScan注解(参数是该Dao所在的包,可以写多个),就可以不用写Mapper注解

package com.cqjtu;

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

@SpringBootApplication
@MapperScan(basePackages = "com.cqjtu.dao") // 使用了这个就不要在StudentDao接口中写@Mapper
public class Application
{

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

}

运行程序成功后,在浏览器地址栏输入http://localhost:9001/orm/student/query?id=3就可以查询到

在SpringBoot框架中集成MyBatis_xml_06

参数id可以换