SpringBoot整合Mybatis

1、新建springboot项目

在这里插入图片描述
在这里插入图片描述

2、添加项目所需要的依赖

我这里是直接在创建的时候勾选的,当然后续也可以在pom文件中再添加或修改
需要注意的是springboot版本跟mybatis版本问题,要对应上,否则也会出现问题
在这里插入图片描述
自动生成的配置文件
在这里插入图片描述

3、编写配置

两方面配置,一个是在springboot的yml文件中进行配置,另一个是在mybatis的配置文件中配置(可以不写配置内容,但一定要有这个配置文件,否则运行时会报错)

3.1 Springboot配置文件

spring:
  datasource: #数据源配置
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test_student?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

mybatis:
  mapper-locations: classpath:static/mybatis/mapper/*.xml #MyBatis Mapper文件所在位置。
  config-location: classpath:static/mybatis/mybatis-config.xml  #MyBatis全局配置文件所在位置
  type-aliases-package: com.example.student.pojo #需要自动扫描的 Java Bean 所在包路径


注意:这里面的路径,都要根据自己的实际情况进行修改

3.2 mybatis的配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!--    日志配置-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 指定日志输出实现类 -->
    </settings>
    <typeAliases>
        <!-- 类型别名配置 -->
    </typeAliases>
    <mappers>
        <!-- Mapper配置 -->
    </mappers>
</configuration>

4、编码

目录结构

在这里插入图片描述

TbClass

package com.example.student.pojo;

public class TbClass {
    private Integer classId;
    private String className;
    private String classGrade;
    private String headTeacher;

    //构造方法,getter setter方法
}

TbClassMapper.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.student.mapper.TbClassMapper">
    <resultMap id="tbClassMap" type="com.example.student.pojo.TbClass">
        <id property="classId" column="class_id" />
        <result property="className" column="class_name" />
        <result property="classGrade" column="class_grade" />
        <result property="headTeacher" column="head_teacher" />
    </resultMap>
<!--property是实体类中的属性名称,column是数据库表中属性名称-->
    <select id="getAll" resultMap="tbClassMap">
        select * from tb_class
    </select>

</mapper>

TbClassMapper

package com.example.student.mapper;

import com.example.student.pojo.TbClass;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface TbClassMapper {

    /**
     * 查询所有班级信息
     * @return
     */
    public List<TbClass> getAll();

}

注意:这里的方法名,要跟对应的xml文件中的id名称一致。

TbClassService

package com.example.student.service;

import com.example.student.pojo.TbClass;

import java.util.List;

public interface TbClassService {
    /**
     * 查询所有班级信息
     * @return
     */
    public List<TbClass> getAll();
}

TbClassServiceImpl

package com.example.student.service.impl;

import com.example.student.mapper.TbClassMapper;
import com.example.student.pojo.TbClass;
import com.example.student.service.TbClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TbClassServiceImpl implements TbClassService {
    @Autowired
    private TbClassMapper tbClassMapper;


    /**
     * 查询所有班级信息
     * @return
     */
    public List<TbClass> getAll(){
        return tbClassMapper.getAll();
    }

}

TbClassController

package com.example.student.controller;

import com.example.student.pojo.TbClass;
import com.example.student.service.TbClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class TbClassController {
    @Autowired
    private TbClassService tbClassService;

    @GetMapping("/class/getAll")
    /**
     * 查询所有班级信息
     * @return
     */
    public List<TbClass> getAll(){
        return tbClassService.getAll();
    }
}



5、查询结果展示

在这里插入图片描述

6、可能会遇到的问题:

6.1 启动时报错

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-06-08 19:58:16.547 ERROR 12888 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tbClassController': Unsatisfied dependency expressed through field 'tbClassService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tbClassServiceImpl': Unsatisfied dependency expressed through field 'tbClassMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tbClassMapper' defined in file [D:\test\student\target\classes\com\example\student\mapper\TbClassMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is java.io.FileNotFoundException: class path resource [static/mybatis/mybatis-config.xml] cannot be opened because it does not exist
	

这个报错是Spring Boot应用程序启动时发生的错误,可能是由于依赖项注入问题导致的。从报错信息中可以看出,应用程序无法找到mybatis-config.xml文件。这可能是因为该文件不存在或路径不正确。

要解决此问题,请按照以下步骤操作:

  1. 确认mybatis-config.xml文件是否存在于项目的static/mybatis目录中。如果不存在,请将其添加到该目录中。

  2. 确认mybatis-config.xml文件的路径是否正确。在报错信息中,可以看到该文件的路径为static/mybatis/mybatis-config.xml。请确保该路径与实际路径相匹配。

  3. 如果仍然无法解决问题,请检查您的依赖项是否正确配置。可能需要添加mybatis-spring-boot-starter依赖项。

  4. 如果仍然无法解决问题,请启用调试模式并查看更详细的错误信息。在启动应用程序时,使用–debug选项启用调试模式。

6.2 在页面上看不到json数据

如果你已经在控制器类上添加了@RestController注解,那么你不需要再在控制器方法上添加@ResponseBody注解了。因为@RestController注解已经包含了@ResponseBody注解的功能,它会将控制器方法返回的对象转换为JSON格式的数据。

如果你已经在控制器类上添加了@RestController注解,但是仍然无法在页面中看到JSON格式的数据对象,可能是因为访问的URL不正确,或者返回的数据为空。你可以按照以下步骤进行操作,以检查问题所在:

  1. 确认访问的URL是否正确。你可以在浏览器中直接访问控制器方法的URL,以查看返回的JSON格式的数据。例如,如果你的控制器方法的URL是/class/1,则可以在浏览器中访问http://localhost:8080/class/1,以获取id为1的TbClass对象的JSON格式数据。

  2. 确认控制器方法返回的数据是否为空。你可以在控制器方法中添加日志输出或者调试断点,以查看返回的TbClass对象是否为空。如果返回的数据为空,那么可能是因为查询条件不正确,或者数据库中没有对应的数据。

总之,如果你已经在控制器类上添加了@RestController注解,但是仍然无法在页面中看到JSON格式的数据对象,你需要检查访问的URL是否正确,以及控制器方法返回的数据是否为空。
【检查映射跟配置文件】

有几个细节点需要注意:
1、配置文件路径
2、对象映射关系

7、附录(附上建表语句跟插入数据)

-- 创建班级表
CREATE TABLE tb_class (
  class_id INT PRIMARY KEY AUTO_INCREMENT,
  class_name VARCHAR(50) NOT NULL,
  class_grade VARCHAR(10) NOT NULL,
  head_teacher VARCHAR(50) NOT NULL
);

-- 插入班级表的数据
INSERT INTO tb_class (class_id, class_name, class_grade, head_teacher)
VALUES 
  (1, '高一一班', '高一', '范闲'),
  (2, '高一二班', '高一', '林婉儿'),
  (3, '高一三班', '高一', '庆帝'),
  (4, '高二一班', '高二', '陈萍萍'),
  (5, '高二二班', '高二', '海棠朵朵'),
  (6, '高二三班', '高二', '范若若'),
  (7, '高三一班', '高三', '司理理'),
  (8, '高三二班', '高三', '战豆豆'),
  (9, '高三三班', '高三', '言冰云');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

丿BAIKAL巛

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值