3.Spring Boot中使用MyBatis

本文详细介绍如何在SpringBoot项目中整合MyBatis框架,包括引入依赖、配置数据源(如Druid)、创建实体类、定义Mapper接口及其实现,以及通过Controller进行测试。

Spring Boot中使用MyBatis

整合MyBatis之前,先搭建一个基本的Spring Boot项目开启Spring Boot。然后引入mybatis-spring-boot-starter和数据库连接驱动(这里使用关系型数据库MySQL 5.7.27)。

mybatis-spring-boot-starter

在pom中引入:

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

不同版本的Spring Boot和MyBatis版本对应不一样,具体可查看官方文档

通过dependency:tree命令查看mybatis-spring-boot-starter都有哪些隐性依赖:
在这里插入图片描述

	[INFO] +- org.mybatis.spring.boot:mybatis-spring-boot-starter:jar:2.1.0:compile
	[INFO] |  +- org.springframework.boot:spring-boot-starter-jdbc:jar:2.1.7.RELEASE:compile
	[INFO] |  |  +- com.zaxxer:HikariCP:jar:3.2.0:compile
	[INFO] |  |  \- org.springframework:spring-jdbc:jar:5.1.9.RELEASE:compile
	[INFO] |  |     \- org.springframework:spring-tx:jar:5.1.9.RELEASE:compile
	[INFO] |  +- org.mybatis.spring.boot:mybatis-spring-boot-autoconfigure:jar:2.1.0:compile
	[INFO] |  +- org.mybatis:mybatis:jar:3.5.2:compile
	[INFO] |  \- org.mybatis:mybatis-spring:jar:2.0.2:compile

可发现其包含了spring-boot-starter-jdbc依赖,默认使用tomcat-jdbc数据源。

引入mysql-connector

在pom中引入:

 <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
  </dependency>
Druid数据源

Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目Druid。Druid不但提供连接池的功能,还提供监控功能,可以实时查看数据库连接池和SQL查询的工作情况。

  • 配置Druid依赖
    Druid为Spring Boot项目提供了对应的starter:
<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.18</version>
 </dependency>
  • Druid数据源配置

上面通过dependency:tree命令查看mybatis starter的隐性依赖发现,Spring Boot的数据源配置的默认类型是org.apache.tomcat.jdbc.pool.Datasource,为了使用Druid连接池,需要在application.yml下配置:

 servlet:
    context-path: /web

spring:
  datasource:
    druid:
      # 数据库访问配置, 使用druid数据源
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/testspringall?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
      username: root
      password: root
      # 连接池配置
      initial-size: 5
      min-idle: 5
      max-active: 20
      # 连接等待超时时间
      max-wait: 30000
      # 配置检测可以关闭的空闲连接间隔时间
      time-between-eviction-runs-millis: 60000
      # 配置连接在池中的最小生存时间
      min-evictable-idle-time-millis: 300000
      validation-query: select '1' from dual
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
      filters: stat,wall
      # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
      aop-patterns: com.springboot.servie.*


  # WebStatFilter配置
  web-stat-filter:
    enabled: true
    # 添加过滤规则
    url-pattern: /*
    # 忽略过滤的格式
    exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

  # StatViewServlet配置
  stat-view-servlet:
    enabled: true
    # 访问路径为/druid时,跳转到StatViewServlet
    url-pattern: /druid/*
    # 是否能够重置数据
    reset-enable: false
    # 需要账号密码才能访问控制台
    login-username: druid
    login-password: druid123
    # IP白名单
    # allow: 127.0.0.1
    # IP黑名单(共同存在时,deny优先于allow)
    # deny: 192.168.1.218

  # 配置StatFilter
  filter:
    stat:
      log-slow-sql: true

jpa:
	show-sql: true
	hibernate:
  		ddl-auto: update

上述配置不但配置了Druid作为连接池,而且还开启了Druid的监控功能。 其他配置可参考官方wiki

配置完成之后,运行项目,并访问http://localhost:8080/web/druid:
在这里插入图片描述
输入账号密码即可看到Druid监控后台:
在这里插入图片描述
关于Druid的更多说明,可查看官方wiki参考项

使用MyBatis

使用的库表:

##testspringall为数据库名称,上边yml中muysql链接中记得要指定数据库哦~
CREATE TABLE "testspringall"."STUDENT" (
    "SNO" VARCHAR(3) NOT NULL ,
    "SNAME" VARCHAR(9) NOT NULL ,
    "SSEX" CHAR(2) NOT NULL 
);

INSERT INTO "testspringall"."STUDENT" VALUES ('001', 'KangKang', 'M ');
INSERT INTO "testspringall"."STUDENT" VALUES ('002', 'Mike', 'M ');
INSERT INTO "testspringall"."STUDENT" VALUES ('003', 'Jane', 'F ');

创建对应实体:

public class Student implements Serializable{
    private static final long serialVersionUID = -339516038496531943L;
    private String sno;
    private String name;
    private String sex;
    // get,set略
}

创建一个包含基本CRUD的StudentMapper:

public interface StudentMapper {
    int add(Student student);
    int update(Student student);
    int deleteByIds(String sno);
    Student queryStudentById(Long id);
}

StudentMapper的实现可以基于xml也可以基于注解。

  • 使用注解方式
    继续编辑StudentMapper:
@Component
@Mapper
public interface StudentMapper {
    @Insert("insert into student(sno,sname,ssex) values(#{sno},#{name},#{sex})")
    int add(Student student);
    
    @Update("update student set sname=#{name},ssex=#{sex} where sno=#{sno}")
    int update(Student student);
    
    @Delete("delete from student where sno=#{sno}")
    int deleteBysno(String sno);
    
    @Select("select * from student where sno=#{sno}")
    @Results(id = "student",value= {
        @Result(property = "sno", column = "sno", javaType = String.class),
        @Result(property = "name", column = "sname", javaType = String.class),
        @Result(property = "sex", column = "ssex", javaType = String.class)
    })
    Student queryStudentBySno(String sno);

简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可,动态SQL语句需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。具体可参考MyBatis官方文档

  • 使用xml方式
    使用xml方式需要在application.yml中进行一些额外的配置:
    在这里插入图片描述
测试

接下来编写Service:

 public interface StudentService {
  int add(Student student);
  int update(Student student);
  int deleteBysno(String sno);
  Student queryStudentBySno(String sno);
}

实现类:

@Service("studentService")
public class StudentServiceImp implements StudentService {

	@Autowired
	private StudentMapper studentMapper;
	
	@Override
	public int add(Student student) {
		return this.studentMapper.add(student);
	}

	@Override
	public int update(Student student) {
		return this.studentMapper.update(student);
	}

	@Override
	public int deleteBysno(String sno) {
		return this.studentMapper.deleteBysno(sno);
	}

	@Override
	public Student queryStudentBySno(String sno) {
		return this.studentMapper.queryStudentBySno(sno);
	}
}

编写controller:

@RestController
public class TestController {

	@Autowired
	private StudentService studentService;
	
	@RequestMapping( value = "/querystudent", method = RequestMethod.GET)
	public Student queryStudentBySno(String sno) {
		return this.studentService.queryStudentBySno(sno);
	}
}

完整的项目目录如下图所示:
在这里插入图片描述
启动项目访问:http://localhost:8080/web/querystudent?sno=001:
在这里插入图片描述
查看SQL监控情况:
在这里插入图片描述
可看到其记录的就是刚刚访问/querystudent得到的SQL。
这里比较蛋疼的是这个SQL还不能直接完整查看【必须通过点击红色框中的超链接进去查看或者鼠标放在链接上查看】。

source code
<think>我们正在解决一个关于Spring Boot项目中MyBatis依赖未找到的问题。用户遇到了一个错误:Dependency &#39;org.mybatis.spring.boot:mybatis-spring-boot-starter:3.5.4&#39; not found。这通常发生在Maven或Gradle项目中,当构建工具无法从配置的仓库中下载该依赖时。 可能的原因包括: 1. 依赖版本不存在:检查该版本是否在Maven中央仓库或配置的仓库中存在。 2. 仓库配置问题:项目的构建文件(pom.xml或build.gradle)中没有正确配置仓库,或者网络问题导致无法访问仓库。 3. 拼写错误:依赖的groupId、artifactId或版本号可能有拼写错误。 解决方案步骤: 1. 检查依赖版本是否存在:访问Maven中央仓库(https://mvnrepository.com/)搜索`mybatis-spring-boot-starter`,确认版本`3.5.4`是否存在。 2. 如果版本不存在,选择一个存在的版本进行替换。 3. 检查仓库配置:确保构建文件中配置了正确的仓库(如Maven中央仓库)。对于Spring Boot项目,通常不需要额外配置,因为Maven中央仓库是默认的。 4. 清理构建工具缓存:有时候本地仓库的缓存可能导致问题,可以尝试清理(如Maven的`mvn dependency:purge-local-repository`或删除本地仓库中对应的文件夹)并重新构建。 根据引用[1],我们知道在较早的版本中(如1.2.0)是存在的,但用户使用的是3.5.4,所以我们需要检查该版本是否存在。 实际步骤: 1. 访问Maven中央仓库,搜索`mybatis-spring-boot-starter`,我们发现最新版本(截至2023年)是3.0.x,而3.5.4这个版本并不存在。因此,可能是用户写错了版本号。 所以,正确的做法是使用一个可用的版本,例如3.0.1(根据当前时间选择最新稳定版)。在Maven中央仓库中,我们查看该依赖的可用版本,选择其中一个。 因此,在pom.xml中,我们应该使用一个存在的版本,例如: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.1</version> </dependency> ``` 如果用户使用的是Gradle,则在build.gradle中: ```groovy implementation &#39;org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.1&#39; ``` 注意:版本号需要根据实际情况调整,建议使用最新稳定版。 另外,如果项目使用的是Spring Boot,通常不需要指定版本号,因为Spring Boot的父POM或依赖管理插件(如spring-boot-starter-parent)已经管理了版本。因此,可以省略版本号,让Spring Boot自动管理: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> ``` 在Gradle中,如果使用Spring Boot的依赖管理插件,也可以省略版本号。 总结: 1. 检查并修正依赖版本为可用版本(如3.0.1)。 2. 或者省略版本号,由Spring Boot管理。 如果问题仍然存在,检查网络连接和仓库配置。 最后,建议用户更新Spring Boot到较新版本,以获得更好的兼容性。</think>### 解决 Spring Boot 项目中 MyBatis 依赖未找到错误 当出现 `Dependency &#39;org.mybatis.spring.boot:mybatis-spring-boot-starter:3.5.4&#39; not found` 错误时,通常由以下原因导致: #### 1. **版本号不存在**(最常见原因) - MyBatis 官方未发布 `3.5.4` 版本(截至2023年) - 当前最新稳定版为 `3.0.2`(202310月更新) - 解决方案: ```xml <!-- 使用正确版本 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.2</version> <!-- 修正版本号 --> </dependency> ``` #### 2. **仓库配置缺失** - 检查 `pom.xml` 是否配置 Maven 中央仓库: ```xml <repositories> <repository> <id>central</id> <url>https://repo.maven.apache.org/maven2</url> </repository> </repositories> ``` #### 3. **依赖作用域错误** - 确保依赖未放在 `<dependencyManagement>` 中却不声明版本: ```xml <!-- 错误示例 --> <dependencyManagement> <dependencies> <dependency> <!-- 此处缺少版本号 --> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> </dependencies> </dependencyManagement> ``` #### 4. **本地缓存问题** 执行清理命令: ```bash mvn clean install -U # -U 强制更新快照 ``` 或手动删除本地仓库缓存: ```bash rm -rf ~/.m2/repository/org/mybatis/spring/boot/ ``` #### 完整配置示例 ```xml <project> <!-- 父项目使用 Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.1.5</version> <!-- 使用兼容版本 --> </parent> <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.2</version> <!-- 官方最新稳定版 --> </dependency> </dependencies> </project> ``` > **注意**:MyBatis Spring Boot Starter 3.x 仅兼容 Spring Boot 3.x,若使用 Spring Boot 2.x 需降级到 `2.3.1`[^1] --- ### 相关问题 1. **如何查看 MyBatis Spring Boot Starter 的最新版本?** `建议方案`:访问 [Maven Central Repository](https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter) 或执行 `mvn versions:display-dependency-updates` 2. **Spring Boot 3.x 与 MyBatis 的兼容性如何配置?** `关键点`:需使用 MyBatis Starter 3.x + Java 17+,避免与 Spring Boot 2.x 混用 3. **依赖下载失败但版本号正确该如何处理?** `排查步骤`: - 检查网络是否可访问 `repo.maven.apache.org` - 验证 Maven `settings.xml` 是否配置代理或镜像仓库 - 执行 `mvn dependency:resolve -Dartifact=org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.2` 4. **如何解决 MyBatisSpring Boot 版本冲突?** `推荐方案`:使用 Spring Boot 的 BOM 管理依赖版本: ```xml <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>3.1.5</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> ``` [^1]: 引用来源:MyBatis 官方文档版本兼容性说明
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值