行业知识
五分钟解决Springboot整合Mybaties
2026-11-04 02:58:26
来源:互联网转载
SpringBoot整合Mybaties
- 创建maven工程
- 整合mybaties
- 逆向代码生成
创建maven工程
·1.通过idea创建maven工程如下图
2.生成的工程如下
这里主要分为三步:添加依赖,增加配置,增加注解
1.添加依赖
org.springframework.boot spring-boot-starter-parent 2.5.4 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test
2.添加配置文件application.yml,增加端口号
3.修改启动类.增加@SpringBootApplication注解
和修改主类SpringApplication.run(Main.class,args);如下
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Main { public static void main(String[] args) { SpringApplication.run(Main.class,args); }}通过以上三步,恭喜springboot项目搭建完成,运行看下效果
整合mybaties
springboot整合任何中间件都是三步:依赖,配置,注解
1.依赖:
org.mybatis mybatis 3.5.5 org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.0 org.mybatis.generator mybatis-generator-core 1.3.7 mysql mysql-connector-java 8.0.21
这里引入了三个依赖:第一个是springboot整合mybaties依赖,后面两个是逆向工程的相关依赖
2.配置增加如下配置到配置文件,根据需要修改用户名密码和数据库,并且注意mapper-locations: classpath:mappers/*.xml的mappers路径
spring: datasource: url: jdbc:mysql://localhost:3306/course?useSSL=false&serverTimezone=GMT username: root password: 565#指定mybatis映射文件的地址mybatis: mapper-locations: classpath:mappers/*.xml
2.注解
@Mapper,这里先用这个注解,在所有Mapper下的文件都加上该注解如下
逆向代码生成
增加配置
这个路径要写自己jar包的路径
2.引入插件
在pom.xml中加入
${artifactId} org.mybatis.generator mybatis-generator-maven-plugin 1.3.7 src/main/resources/generatorConfig.xml true true org.springframework.boot spring-boot-maven-plugin如下所示:
加入之后maven插件如下所示
运行之后会生成代码,目录结构:
再次启动项目确认启动成功:
至此我们的整合工作结束
测试一下,创建一个controller包,并创建类UserController
package edu.hbgy.rjz.controller;import edu.hbgy.rjz.dao.UserMapper;import edu.hbgy.rjz.entity.User;import edu.hbgy.rjz.entity.UserExample;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.List;@RestControllerpublic class UserController { @Resource private UserMapper userMapper; @RequestMapping(value="user/del", method = RequestMethod.POST) public Integer del(@RequestBody User user){ UserExample example = new UserExample(); example.createCriteria().andIdEqualTo(user.getId()); Integer count = userMapper.deleteByExample(example); return count; }}启动运行: