Spring Boot与MyBatis完美融合:整合实战指南

本文详细介绍了如何在SpringBoot项目中整合MyBatis,涉及环境搭建、依赖管理、配置Druid数据源、案例演示以及MyBatis-Plus报错分析和解决方案,包括依赖问题、配置错误、接口与XML映射等关键环节。
摘要由CSDN通过智能技术生成

目录

1、梳理整合思路

2、整合实现

2.1 环境搭建

2.2 案例

3、整合mybatis-plus报错

1. 依赖问题

2. 配置问题

3. Mapper接口与XML文件问题

4. 实体类问题

5. 数据库连接问题

6. SQL语句问题

7. Spring容器问题

8. 其他


1、梳理整合思路

  1. 将MyBatis的DataSource交给Spring IoC容器创建并管理,使用第三方数据库连接池(Druid,C3P0等)代替MyBatis内置的数据库连接池
  2. 将MyBatis的SqlSessionFactory交给Spring IoC容器创建并管理,使用spring-mybatis整合jar包中提供的SqlSessionFactoryBean类代替项目中的MyBatisUtil工具类
  3. 将MyBatis的接口代理方式生成的实现类,交给Spring IoC容器创建并管理

mybatis框架开发步骤

定义mapper接口,定义方法
定义mapper.xml映射文件
创建mybatis核心配置文件
创建SqlSession对象,使用该对象生成mapper接口的代理对象执行方法

spring整合mybatis的核心就是把mybatis开发用到的对象交由spring容器ioc来创建,这样就做到了整合的目的。
在开发中,我们一般不使用mybatis自带的数据源,而是使用别的数据源,比如c3p0,dbcp等,本人使用的是阿里的druid数据源。

2、整合实现

2.1 环境搭建

导入相关依赖:

<dependencies>
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--spring核心ioc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!--mybatis和spring集成的依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <!--阿里公司的数据库连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
  </dependencies>

  <build>
    <!--目的是把src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中-->
    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <!--指定jdk的版本-->
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

重点是注意resources标签的配置,很多人都是在这里出错导致程序运行报错找不到mapper.xml文件

2.2 案例

本案例从student表中查询学生和新增学生功能。

//实体类Student
public class Student {
    private int stuNo;
    private String stuName;
    private int cardID;
    private int classID;
    public Student() {
    }
    public Student(int stuNo, String stuName, int cardID, int classID) {
        this.stuNo = stuNo;
        this.stuName = stuName;
        this.cardID = cardID;
        this.classID = classID;
    }
    public int getStuNo() {
        return stuNo;
    }
    public void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public int getCardID() {
        return cardID;
    }
    public void setCardID(int cardID) {
        this.cardID = cardID;
    }
    public int getClassID() {
        return classID;
    }
    public void setClassID(int classID) {
        this.classID = classID;
    }
    @Override
    public String toString() {
        return "Student{" +
                "stuNo=" + stuNo +
                ", stuName='" + stuName + '\'' +
                ", cardID=" + cardID +
                ", classID=" + classID +
                '}';
    }
}

mapper接口

public interface StudentMapper {
    //查询全部
    List<Student> queryAll();
    //新增学生
    void addStudent(Student student);
}

mapper.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.mms.mapper.StudentMapper">

    <!--查询全部-->
    <select id="queryAll" resultType="Student">
        select * from student
    </select>

    <!--新增学生-->
    <insert id="addStudent" parameterType="Student">
        insert into student (stuno,stuname,cardid,classid)
        values (#{stuNo},#{stuName},#{cardID},#{classID})
    </insert>
</mapper>

service接口

public interface IStudentService {
    List<Student> queryAll();
    void addStudent(Student student);
}

service实现类

public class StudentServiceImpl implements IStudentService {
    //mapper属性
    private StudentMapper mapper;
    //set注入给mapper对象赋值
    public void setMapper(StudentMapper mapper) {
        this.mapper = mapper;
    }
    
    @Override
    public List<Student> queryAll() {
        return mapper.queryAll();
    }

    @Override
    public void addStudent(Student student) {
        mapper.addStudent(student);
    }
}

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>
    <typeAliases>
        <!--
            批量设置别名,会自动的将该包下的所有类定义了别名,别名就是其自身且不区分大小
        -->
        <package name="com.mms.entity" />
    </typeAliases>
    <!--加载映射配置文件-->
    <mappers>
        <mapper resource="com/mms/mapper/studentMapper.xml"></mapper>
    </mappers>
</configuration>

在这里由于数据源对象我们是交由spring容器托管了,因此mybatsi核心配置文件中就没有environments标签了。

spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--加载数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--声明数据源-->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!--set注入给数据库信息赋值,不需要指定驱动类,sprinf根据url自动识别
        <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&amp;useSSL=true&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="333"/>-->

        <!--使用db配置文件读取数据库信息,格式类似el表达式-->
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

    <!--声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--set注入赋值-->
        <!--set注入,把数据库连接池付给了dataSource属性-->
        <property name="dataSource" ref="myDataSource" />
        <!--mybatis主配置文件的位置
           configLocation属性是Resource类型,读取配置文件
           它的赋值,使用value,指定文件的路径,使用classpath:表示文件的位置
        -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>

    <!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)
        MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象。
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定SqlSessionFactory对象的id-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!--指定包名, 包名是dao接口所在的包名。
            MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行
            一次getMapper()方法,得到每个接口的dao对象。
            创建好的dao对象放入到spring的容器中的。 dao对象的默认名称是 接口名首字母小写
        -->
        <property name="basePackage" value="com.mms.mapper"/>
    </bean>

    <!--声明service-->
    <bean id="studentServiceImpl" class="com.mms.service.impl.StudentServiceImpl">
        <property name="mapper" ref="studentMapper"/>
    </bean>
</beans>

数据库配置文件

url = jdbc:mysql://localhost:3306/Xxx?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
username = Xxx
password = Xxx

测试

    //执行查询全部,不使用service
    @Test
    public void test02() {
        String config = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(config);
        //获取mapper的代理对象
        StudentMapper mapper = (StudentMapper) ac.getBean("studentMapper");
        List<Student> students = mapper.queryAll();
        for (Student student : students) {
            System.out.println("student--->"+student);
        }
    }

    //执行增加学生,使用service
    @Test
    public void test03() {
        String config = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(config);
        //获取service对象
        IStudentService service = (IStudentService) ac.getBean("studentServiceImpl");
        Student student = new Student();
        student.setStuName("呵呵");
        student.setStuNo(1111);
        student.setCardID(1115);
        student.setClassID(1);
        service.addStudent(student);

    }

3、整合mybatis-plus报错

1. 依赖问题

  • 依赖未正确添加:确保在pom.xmlbuild.gradle中添加了MyBatis-Plus的依赖。
  • 版本不兼容:使用的MyBatis-Plus版本与Spring Boot版本不兼容。请检查并更新为兼容的版本。

2. 配置问题

  • 配置文件缺失或错误:确保application.propertiesapplication.yml中有正确的MyBatis-Plus配置。
  • Mapper扫描路径错误@MapperScan注解指定的路径与Mapper接口所在包不一致。

3. Mapper接口与XML文件问题

  • Mapper接口未标注:Mapper接口未使用@Mapper@Repository注解标注。
  • XML文件位置错误:XML文件位置与配置文件中指定的位置不一致。
  • XML文件命名空间错误:XML文件中的namespace与Mapper接口的全路径不一致。

4. 实体类问题

  • 实体类注解缺失或错误:如@TableName@TableId等注解未使用或使用错误。
  • 字段类型不匹配:数据库字段类型与实体类字段类型不匹配。

5. 数据库连接问题

  • 数据库URL错误:数据库URL、用户名、密码等配置错误。
  • 驱动未添加:未添加数据库驱动依赖。

6. SQL语句问题

  • SQL语句错误:XML文件中的SQL语句语法错误或逻辑错误。
  • 占位符错误:在SQL语句中使用了错误的占位符。

7. Spring容器问题

  • Bean创建失败:由于配置错误或依赖问题,Spring容器无法创建所需的Bean。
  • 循环依赖:Bean之间存在循环依赖,导致Spring容器无法初始化。

8. 其他

  • IDE或构建工具问题:IDE或构建工具缓存导致的问题,可以尝试清理缓存并重新构建项目。
  • 代码错误:代码中存在逻辑错误或语法错误。
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot整合MyBatis可以使用MyBatis-Spring-Boot-Starter来简化配置和集成过程。首先,你需要在项目的pom.xml文件中引入MyBatis-Spring-Boot-Starter的依赖。你可以在依赖中添加以下代码来引入MyBatis-Spring-Boot-Starter的依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> ``` 引用\[1\] 这样,你就成功引入了MyBatis-Spring-Boot-Starter的依赖。接下来,你需要在Spring Boot配置文件中配置数据库连接信息和MyBatis的相关配置。你可以在application.properties或application.yml文件中添加以下配置: ``` spring.datasource.url=jdbc:mysql://localhost:3306/db_name spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.model ``` 其中,你需要将`db_name`替换为你的数据库名称,`username`和`password`替换为你的数据库用户名和密码。`com.example.model`是你的实体类所在的包路径,`mapper/*.xml`是你的Mapper文件所在的路径。你可以根据自己的项目需求进行相应的配置。引用\[2\] 完成以上配置后,你可以编写MyBatis的Mapper接口和对应的Mapper XML文件来定义数据库操作。你可以在Mapper接口中使用注解或XML配置SQL语句。例如,你可以编写一个查询用户信息的接口: ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(int id); } ``` 在Mapper XML文件中,你可以编写具体的SQL语句: ```xml <mapper namespace="com.example.mapper.UserMapper"> <select id="getUserById" resultType="com.example.model.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper> ``` 这样,你就完成了Spring BootMyBatis整合。你可以通过调用Mapper接口中的方法来进行数据库操作。引用\[3\] #### 引用[.reference_title] - *1* *2* *3* [SpringBoot + MyBatis 结合 MVC框架设计 第1关:项目整合 - SpringBoot + MyBatis](https://blog.csdn.net/ycq0_9/article/details/127832774)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Yaml墨韵

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

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

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

打赏作者

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

抵扣说明:

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

余额充值