SpringBoot整合MyBatis,入门教程,细节无敌,不能错过

在这里插入图片描述

需求

SpringBoot整合MyBatis。

实现步骤

  1. 搭建SpringBoot工程
  2. 引入mybatis起步依赖、添加mysql驱动
  3. 编写DataSource和MyBatis相关配置
  4. 定义表和实体类
  5. 编写dao和mapper文件/纯注解开发
  6. 测试

惨痛的教训

同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
src>main>resources>application.yml
无论 application.ymlapplication.yamlapplication.properties文件只能有一个

1. 搭建SpringBoot工程

在这里插入图片描述
点击Next,下一步

2. 引入mybatis起步依赖、添加mysql驱动

弹出下图弹窗,分别勾选My Batis FrameworkMySQL Driver
然后点击Create,完成创建
在这里插入图片描述

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>
    <groupId>jjycheng.SpringBootWebDemo</groupId>
    <artifactId>SpringBoot_MyBatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot_MyBatis</name>
    <description>SpringBoot_MyBatis</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.6.13</spring-boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <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>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>jjycheng.springbootwebdemo.springboot_mybatis.SpringBootMyBatisApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

核心代码

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>

3. 编写DataSource和MyBatis相关配置

src》main》resources下面新建一个application.yml 文件
在这里插入图片描述

application.yml 文件内容

spring:
  datasource:
    url: jdbc:mysql:///springbootmybatismysqldb?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

springbootmybatismysqldb是数据库名

4. 定义表和实体类

4.1.定义表

/*
 Navicat Premium Data Transfer

 Source Server         : mysql
 Source Server Type    : MySQL
 Source Server Version : 50726
 Source Host           : localhost:3306
 Source Schema         : springbootmybatismysqldb

 Target Server Type    : MySQL
 Target Server Version : 50726
 File Encoding         : 65001

 Date: 11/08/2024 19:44:29
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for userinfo
-- ----------------------------
DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo`  (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
  `Age` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`Id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of userinfo
-- ----------------------------
INSERT INTO `userinfo` VALUES (1, 'zhangsan', 20);
INSERT INTO `userinfo` VALUES (2, 'lishi', 21);

SET FOREIGN_KEY_CHECKS = 1;

4.2.实体类

在这里插入图片描述

UserInfoModel.java 内容

package jjycheng.springbootwebdemo.springboot_mybatis.domain;

public class UserInfoModel {
    private int Id;
    private String Name;
    private int Age;

    public int getId() {
        return Id;
    }

    public void setId(int id) {
        Id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public int getAge() {
        return Age;
    }

    public void setAge(int age) {
        Age = age;
    }

    @Override
    public String toString() {
        return "UserInfoModel{" +
                "Id=" + Id +
                ", Name='" + Name + '\'' +
                ", Age=" + Age +
                '}';
    }
}

5. 编写dao和mapper文件/纯注解开发

5.1.纯注解开发

5.1.1新建接口

选择新建java class,选择Interface,输入名称mapper.UserInfoMapper
在这里插入图片描述

新建成功后,结构目录如下
在这里插入图片描述

src
 |-java
 	 |-....
        |-domain
      		|-UserInfoModel.java
        |-mapper
            |-UserInfoMapper.java
UserInfoMapper.java内容
package jjycheng.springbootwebdemo.springboot_mybatis.mapper;
import jjycheng.springbootwebdemo.springboot_mybatis.domain.UserInfoModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserInfoMapper {
    @Select("select * from userinfo")
    public List<UserInfoModel> findAll();
}

5.1.2 测试代码

src》test》java下面找到测试文件,
我的文件名是SpringBootMyBatisApplicationTests.java

SpringBootMyBatisApplicationTests.java 文件内容
package jjycheng.springbootwebdemo.springboot_mybatis;

import jjycheng.springbootwebdemo.springboot_mybatis.domain.UserInfoModel;
import jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringBootMyBatisApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    public void TestFindAll()
    {
        List<UserInfoModel> list =userInfoMapper.findAll();
        System.out.println(list);
    }
}

5.1.3运行测试

src》test》java下面找到测试文件,
我的文件名是SpringBootMyBatisApplicationTests.java ,点击测试代码左侧的运行按钮,进行运行测试
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

5.2 xml开发

5.2.1新建接口

选择新建java class,选择Interface,输入名称mapper.UserInfoXmlMapper
在这里插入图片描述

5.2.2此时项目结构截图

在这里插入图片描述

5.2.3.UserInfoXmlMapperjava接口代码

package jjycheng.springbootwebdemo.springboot_mybatis.mapper;

import jjycheng.springbootwebdemo.springboot_mybatis.domain.UserInfoModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserInfoXmlMapper { 
    public List<UserInfoModel> findAll();
}

5.2.4.新建配置文件夹

配置文件一般写到src》main》resources下面
我新建一个文件夹叫mapper
在这里插入图片描述

5.2.5.新建配置文件UserInfoMapper.xml

新建配置文件UserInfoMapper.xml
UserInfoMapper.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="jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoXmlMapper">
    <select id="findAll" resultType="UserInfo">
        select * from userinfo
    </select>

</mapper>

5.2.6.配置文件UserInfoMapper.xml重点代码解读

5.2.6.1namespace
<mapper namespace="jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoXmlMapper">

namespace的内容是xml的接口文件路径
UserInfoXmlMapper.java的文件路径
怎么才能得到这个文件路径呢?

  1. 接口文件顶部的引用包名+接口文件名
    package jjycheng.springbootwebdemo.springboot_mybatis.mapper;
  2. 找解决文件位置,(我的编辑器是IDEA )
    右键接口文件》点击Copy Path/Reference...》出现弹框》点击Copy Reference》就复制成功了
    在这里插入图片描述
    在这里插入图片描述
5.2.6.2.id=“findAll”

select id="findAll"findAll
一定要和接口代码 public List<UserInfoModel> findAll();findAll()方法名一致。

5.2.7.数据库配置文件application.yml配置mybatis

配置后的application.yml内容如下


# DataSource
spring:
  datasource:
    url: jdbc:mysql:///springbootmybatismysqldb?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver


# Mybatis
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml #mapper映射配置文件路径
  type-aliases-package: jjycheng.springbootwebdemo.springboot_mybatis.domain

5.2.8. 运行测试代码

src》test》java下面找到测试文件,
我的文件名是SpringBootMyBatisApplicationTests.java
增加xml的内容

    /*----------xml开发----------*/
    @Autowired
    private UserInfoXmlMapper userInfoXmlMapper;
    @Test
    public void TestXmlFindAll()
    {
        List<UserInfoModel> list =userInfoXmlMapper.findAll();
        System.out.println(list);
    }

SpringBootMyBatisApplicationTests.java 完整内容

package jjycheng.springbootwebdemo.springboot_mybatis;

import jjycheng.springbootwebdemo.springboot_mybatis.domain.UserInfoModel;
import jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoMapper;
import jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoXmlMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringBootMyBatisApplicationTests {

    @Test
    void contextLoads() {
    }

    /*----------注解开发----------*/
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    public void TestFindAll()
    {
        List<UserInfoModel> list =userInfoMapper.findAll();
        System.out.println(list);
    }

    /*----------xml开发----------*/
    @Autowired
    private UserInfoXmlMapper userInfoXmlMapper;
    @Test
    public void TestXmlFindAll()
    {
        List<UserInfoModel> list =userInfoXmlMapper.findAll();
        System.out.println(list);
    }
}

5.2.9. 运行测试

src》test》java下面找到测试文件,
我的文件名是SpringBootMyBatisApplicationTests.java ,点击测试代码左侧的运行按钮,进行运行测试
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
src>main>resources>application.yml
无论 application.ymlapplication.yamlapplication.properties文件只能有一个

在这里插入图片描述

6.完整项目结构截图-【很重要】

.
在这里插入图片描述

6.1核心代码文件-数据库实体模型-UserInfoModel.java

package jjycheng.springbootwebdemo.springboot_mybatis.domain;

public class UserInfoModel {
    private int Id;
    private String Name;
    private int Age;

    public int getId() {
        return Id;
    }

    public void setId(int id) {
        Id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public int getAge() {
        return Age;
    }

    public void setAge(int age) {
        Age = age;
    }

    @Override
    public String toString() {
        return "UserInfoModel{" +
                "Id=" + Id +
                ", Name='" + Name + '\'' +
                ", Age=" + Age +
                '}';
    }
}

6.2核心代码文件-注解开发-映射文件-UserInfoMapper.java

package jjycheng.springbootwebdemo.springboot_mybatis.mapper;
import jjycheng.springbootwebdemo.springboot_mybatis.domain.UserInfoModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserInfoMapper {
    @Select("select * from userinfo")
    public List<UserInfoModel> findAll();
}

6.3核心代码文件-xml开发-映射文件-UserInfoXmlMapper.java

package jjycheng.springbootwebdemo.springboot_mybatis.mapper;

import jjycheng.springbootwebdemo.springboot_mybatis.domain.UserInfoModel;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserInfoXmlMapper {
    public List<UserInfoModel> findAll();
    public List<UserInfoModel> getTop1();
}

6.4核心代码文件-xml开发-xml配置文件-UserInfoMapper.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="jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoXmlMapper">
    <select id="findAll" resultType="UserInfoModel" >
        select * from userinfo
    </select>
    <select id="getTop1" resultType="UserInfoModel" >
        select * from userinfo limit 0,1
    </select>
</mapper>

6.5核心代码文件-配置文件-application.yml

server:
  port: 8081

# DataSource
spring:
  datasource:
    url: jdbc:mysql:///springbootmybatismysqldb?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver


# Mybatis
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: jjycheng.springbootwebdemo.springboot_mybatis.domain

6.6核心代码文件-测试-SpringBootMyBatisApplicationTests.java

package jjycheng.springbootwebdemo.springboot_mybatis;

import jjycheng.springbootwebdemo.springboot_mybatis.domain.UserInfoModel;
import jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoMapper;
import jjycheng.springbootwebdemo.springboot_mybatis.mapper.UserInfoXmlMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@SpringBootTest
public class SpringBootMyBatisApplicationTests {

    @Test
    void contextLoads() {
    }

    /*----------注解开发----------*/
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    public void TestFindAll()
    {
        List<UserInfoModel> list =userInfoMapper.findAll();
        System.out.println(list);
    }

    /*----------xml开发----------*/
    @Autowired
    private UserInfoXmlMapper userInfoXmlMapper;

    @Test
    public void TestXmlFindAll()
    {
        System.out.println(userInfoXmlMapper.findAll());
    }
}

7. 遇到的错误

7.1.错误1

2024-08-11 20:06:05.454 INFO 31348 — [ main] j.s.s.SpringBootMyBatisApplicationTests :
No active profile set, falling back to 1 default profile: “default”
Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

译文:
没有活动配置文件设置,退回到1个默认配置文件:“default”
正在加载类’ com.mysql.jdbc.Driver’。这是不赞成的。新的驱动类是’ com.mysql.cj.jdbc.Driver’。驱动程序通过SPI自动注册,手动加载驱动程序类通常是不必要的。
错误截图如下

在这里插入图片描述
是因为,我们在数据库配置文件引入的driver-class-name
原:

spring:
  datasource:
    url: jdbc:mysql:///springbootmybatismysqldb?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

修改为

spring:
  datasource:
    url: jdbc:mysql:///springbootmybatismysqldb?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

他的大致意思是我们引入的com.mysql.jdbc.Driver太老了,需要替换成com.mysql.cj.jdbc.Driver
修改后重新运行就正常了。

7.2.神奇的错误

如果,是些神奇的错误,且,网络上的解决方案,都不能解决你的问题,请记住下面这段话。

同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
同一个项目里,application.*文件只能有一个,如果有多个 就会出现一些神奇问题
src>main>resources>application.yml
无论 application.ymlapplication.yamlapplication.properties文件只能有一个

  • 15
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橙-极纪元JJY.Cheng

客官,1分钱也是爱,给个赏钱吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值