SpringBoot与Mybatis整合

1.SpringBoot测试

(1)添加依赖

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
     </dependency>

(2)按Shift+CTRL+T生成Junit5测试类

注意:Junit5类上只有@SpringBootTest,像Junit4就要多个@RunWith(SpringRunner.class)

package com.xxxx.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class HelloControllerTest {

    @Autowired
    private HelloController helloController;

    @Test
    public void hello() {
        String hello = helloController.hello();
        System.out.println(hello);
    }
}

2.Spring整合Mybatis

添加mysql驱动依赖

 <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
 </dependency>

添加SpringBoot的Mybatis启动器

注意:这里是需要定义版本,主要是Mybatis官方开发【根据Spring的接口】

 <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.1.1</version>
 </dependency>

application.yml配置

注意:mapper映射注释掉同时需要mapper在一种形式结构目录中

server:
  port: 9999

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3307/user?characterEncoding=utf-8
    username: root
    password: 123456



mybatis:
  type-aliases-package: com.cqgcxy.entity
#  mapper-locations: classpath:com/cqgcxy/mapper/*Mapper.xml

mybatis-config.xml

<?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="mapUnderScoreToCamelCase" value="true" />
    </settings>
</configuration>

创建类

这里的@Data是由lombok提供的

创建mapper接口

编写mapper

在App启动类扫mapper包

最后编写测试类

测试成功

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值