springboot 整合 mybatisplus 操作

99 阅读1分钟
项目版本信息:
jdk 1.8
springboot 2.7.18 
mysql 5.7

注,该项目是在使用 springboot 整合 shiro 工具的时候创建的,所以项目名字可能会有所偏差,但是做笔记时还没有用到 shiro 。

一、添加依赖

<!-- mybatis依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>
<!-- mysql依赖,本地 mysql 版本:5.7-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>
<!-- lombok依赖-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

二、添加配置

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:mapper/*.xml
spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shirodemo?characterEncoding=utf-8&useSSL=false
    username: your_username
    password: your_password
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

三、创建数据库

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `pwd` varchar(50) DEFAULT NULL,
  `rid` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

根据需求向数据库插入数据,以便查询可以用。

四、创建实体类

image.png

五、创建mapper接口

需要继承 BaseMapper 接口,封装了简单的crud。

image.png

六、创建业务层接口,并写出接口实现类

image.png

image.png

这里注意添加 @Service 注解

七、启动类添加 @MapperScan("com.yuqn.shiro_springboot.mapper") 注解,扫描 mapper 包下的接口。

八、添加测试方法

image.png

image.png

注:这里为了方便,默认名字字段唯一,所以就返回一个 User 实体。