Springboot 整合 MyBatisPlus「详细过程」

本文介绍了如何在Springboot环境中整合MyBatis,包括Maven依赖配置、实体类映射、Mapper接口、Service实现及Controller调用,还展示了数据库表结构和配置细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

提要

这里已经将Springboot环境创建好 这里只是整合MyBatis过程

引入Maven依赖

添加MyBatisPlus启动依赖,添加mysql-connector-java依赖

<!-- mybatis-plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1</version>
</dependency>
<!-- mybatis-plus代码生成器 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.1.tmp</version>
</dependency>
<!-- mysql连接 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

添加application.yml配置

mybatis-plus配置项

mybatis-plus:
  # xml文件路径
  mapper-locations: classpath:mapper/*.xml
  # 实体类路径
  type-aliases-package: com.数据库表对应的实体类的路径
  configuration:
    # 驼峰转换
    map-underscore-to-camel-case: true
    # 是否开启缓存
    cache-enabled: false
    # 打印sql
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 全局配置
  global-config:
    # 数据库字段驼峰下划线转换
    db-column-underline: true
    # id自增类型(数据库id自增)
    id-type: 0

mysql配置项

spring:
  datasource:
       driver-class-name: com.mysql.cj.jdbc.Driver
       username: root
       password: stone
       url: jdbc:mysql://ip:3306/库名?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false

添加数据库对应实体类

@Data
@TableName("class_table")
public class ClassPojo {

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @TableField(value = "class_name")
    private String className;

}

添加Mapper文件

@Mapper
public interface ClassMapper extends BaseMapper<ClassPojo> {

}

添加Service接口

public interface ClassVoService extends IService<ClassPojo>  {
    String getClassName(Long id);//自定义方法
}

添加Service实现类

@Component
public class ClassVoServiceImpl extends ServiceImpl<ClassMapper, ClassPojo> implements ClassVoService {
    public String getClassName(Long id){
        ClassPojo byId = getById (id);
        return byId.getClassName ();

    }
}

添加Controller

@RestController
@RequestMapping("/demo")
public class ExcelController {
    @GetMapping("/getbyid")
    public String getbyid(){
        return classVoService.getClassName (1l);
    }
}

补充对应表结构

CREATE TABLE `class_table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '课程id不能为空主键',
  `class_name` varchar(255) NOT NULL COMMENT '课程名称',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
SQL 复制 全屏

表数据如下

id

class_name

1

语文

2

数学

如果本文对你有帮助,别忘记给我个3连 ,点赞,转发,评论,,咱们下期见。

收藏 等于白嫖,点赞才是真情。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值