Spring学习(十五)——SpringBoot整合Mybatis

一、依赖

注意:springboot整合mybatis包中默认依赖mybatis,故不需要再引入mybatis包,以免由于版本不同出现问题。

    <!-- SpringBoot Mybatis -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.3</version>
    </dependency>

    <!--  mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <!-- druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>

二、配置文件

在项目的resources文件夹下面新建:application.yml

配置数据源

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
    username: root
    password: root

配置Mybatis

mybatis:
  mapper-locations: classpath:cool/gjh/mapper/*Mapper.xml
  type-aliases-package: cool.gjh.entity

配置DAO扫描

在入口类上加@MapperScan注解

package cool.gjh.app;

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

/**
 * SpringBoot入口类
 *
 * @author ACE_GJH
 */
@SpringBootApplication
@MapperScan("cool.gjh.dao")
@ComponentScan("cool.gjh")
public class App
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}


三、测试Mybatis

测试类

package cool.gjh.mybatis;

import cool.gjh.app.App;
import cool.gjh.dao.StudentDao;
import cool.gjh.entity.Student;
import org.junit.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;

/**
 * 测试SpringBoot整合Mybatis
 *
 * @author ACE_GJH
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class MybatisTest {

    @Autowired
    private StudentDao studentDao;

    @Test
    public void testDao(){
        List<Student> students = studentDao.selectAll();
        for (Student student : students) {
            System.out.println(student);
        }
    }

}

DAO接口依赖注入报错解决方案

如图,IDEA会出现如下报错:
报错地方
其实代码是没有问题的,而且运行的话也能运行出正确的结果,但是这个报错很不好看,所有取消掉这个“误报”就好了。
在报错的地方按"alt+Enter",如图往下选择。
步骤1
将"ERROR"改为"WARNING",点击"OK"就好了。
在这里插入图片描述

测试结果

结果

四、事务控制

测试未开启事务插入数据

package cool.gjh.mybatis;

import cool.gjh.app.App;
import cool.gjh.dao.StudentDao;
import cool.gjh.entity.Student;
import org.junit.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.Date;
import java.util.List;
import java.util.UUID;

/**
 * 测试SpringBoot整合Mybatis
 *
 * @author ACE_GJH
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class MybatisTest {

    @Autowired
    private StudentDao studentDao;

    @Test
    public void testSelectAll() {
        System.out.println("------开始查询------");
        List<Student> students = studentDao.selectAll();
        for (Student student : students) {
            System.out.println(student);
        }
        System.out.println("------查询完毕------");
    }

    @Test
    public void testInsert() {
        System.out.println("-----开始插入----");
        Student student = new Student();
        student
                .setId(UUID.randomUUID().toString())
                .setName("CSDN")
                .setAge(30)
                .setBirthday(new Date())
                .setSex(false)
                .setHeight(1.65)
                .setWeight(50)
        ;
        studentDao.insert(student);
        System.out.println("-----插入完毕----");
        int error = 1 / 0;
        testSelectAll();
    }

}

测试结果testInsert():
结果1
结果2
可以看出,未开启事务,如果过程中出现了异常,数据还是插入了进来。

测试开启事务插入数据

在类和方法上加入@Transactional控制事务,并在方法上细化事务的传播

package cool.gjh.mybatis;

import cool.gjh.app.App;
import cool.gjh.dao.StudentDao;
import cool.gjh.entity.Student;
import org.junit.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 org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 测试SpringBoot整合Mybatis
 *
 * @author ACE_GJH
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
@Transactional
public class MybatisTest {

    @Autowired
    private StudentDao studentDao;

    @Test
    @Transactional(propagation = Propagation.SUPPORTS)
    public void testSelectAll() {
        System.out.println("------开始查询------");
        List<Student> students = studentDao.selectAll();
        for (Student student : students) {
            System.out.println(student);
        }
        System.out.println("------查询完毕------");
    }

    @Test
    @Transactional(propagation = Propagation.REQUIRED)
    public void testInsert() {
        System.out.println("-----开始插入----");
        Student student = new Student();
        student
                .setId(UUID.randomUUID().toString())
                .setName("CSDN")
                .setAge(30)
                .setBirthday(new Date())
                .setSex(false)
                .setHeight(1.65)
                .setWeight(50)
        ;
        studentDao.insert(student);
        System.out.println("-----插入完毕----");
        int error = 1 / 0;
        testSelectAll();
    }

}

测试结果:
结果1
结果2
可以看到,当加上事务控制后,在整个过程中如果出现了异常,事务可以回滚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SpringBoot整合Mybatis的配置流程可以分为以下步骤: 1. 首先,需要在项目的pom.xml文件中添加相关的依赖,包括mybatis-spring-boot-starterspring-boot-starter-jdbc等。这些依赖可以通过Maven或Gradle进行管理。 2. 接着,需要在应用程序的配置文件(一般是application.yml或application.properties)中进行相关配置。包括数据库连接信息、Mybatis的配置信息等。 3. 然后,创建实体类(entity)来映射数据库表。这些实体类通常使用注解来指定表名、字段名等信息。 4. 接着,创建数据访问对象(dao)接口,定义数据库操作的方法,使用Mybatis的注解或XML文件进行SQL语句的映射。 5. 接下来,创建服务层(service)和控制层(controller)来完成业务逻辑的处理和接口的调用。 6. 最后,在resources目录下创建mapper文件夹,编写对应的mapper接口和XML文件。XML文件中定义了具体的SQL语句,并与dao接口进行映射。 需要注意的是,以上步骤是整合Mybatis的一般配置流程,具体的实现方式可能会根据项目的需求和个人的习惯有所不同。可以参考和中提供的引用内容了解更多关于SpringBoot整合Mybatis的配置流程。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springboot整合mybatis详细步骤](https://blog.csdn.net/kobe_IT/article/details/123548793)[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^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springBoot——SpringBoot 整合 Mybatis 流程](https://blog.csdn.net/DreamPossible20/article/details/128751096)[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^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

郭建華

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

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

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

打赏作者

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

抵扣说明:

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

余额充值