springboot+Mybatis Plus

文章目录

SpringBoot+Mybatis Plus入门

一、Mybatis Plus简介

Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。并且3.X系列支持lambda语法,让我在写条件构造的时候少了很多的"魔法值",从代码结构上更简洁了.

二、使用步骤

我这里以操作user对象为例

一、引入依赖

注意: SpringBoot 3.0 需要 mybatis-spring 3.0.X 版本,否则会报如下错误:
Invalid value type for attribute 'factoryBeanObjectType''': java.lang.String

java 复制代码
<!--mybatis-plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1</version>
</dependency>

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

二、配置数据源

xml 复制代码
server:
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_demo?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC&useSSL=true
    username: root
    password: 1234

#开启日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

注意修改自己的数据库和用户名密码

三、创建对应的类

实体类

java 复制代码
/**
 * @author ning0
 * @date 2024/8/1 18:54
 * @description UserEntity
 **/
@Data
@TableName("user")
public class UserEntity {
    @TableId(type = IdType.AUTO)
    private Long id;
    @TableField("name")
    private String name;
    @TableField("password")
    private String password;
}

UserMapper注意需要继承BaseMapper

java 复制代码
/**
 * @author ning0
 * @date 2024/8/1 18:56
 * @description UserMapper
 **/

@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}

UserService注意需要继承IService

java 复制代码
public interface UserService extends IService<UserEntity> {
    public UserEntity getUserById(Long id);
}

UserServiceImpl注意需要继承ServiceImpl并实现UserService接口

java 复制代码
/**
 * @author ning0
 * @date 2024/8/1 18:58
 * @description UserServiceImpl
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    @Override
    public UserEntity getUserById(Long id) {
        return this.getById(id);
    }
}

最后自行进行测试就好

相关推荐
新world4 小时前
mybatis-plus从入门到入土(二):单元测试
单元测试·log4j·mybatis
RainbowSea8 小时前
问题 1:MyBatis-plus-3.5.9 的分页功能修复
java·spring boot·mybatis
JAVA学习通10 小时前
Mybatis----留言板
mybatis
双力臂40418 小时前
MyBatis动态SQL进阶:复杂查询与性能优化实战
java·sql·性能优化·mybatis
慕y27420 小时前
Java学习第十五部分——MyBatis
java·学习·mybatis
一勺菠萝丶1 天前
Spring Boot + MyBatis/MyBatis Plus:XML中循环处理List参数的终极指南
xml·spring boot·mybatis
coding and coffee1 天前
狂神说 - Mybatis 学习笔记 --下
java·后端·mybatis
耀耀_很无聊2 天前
07_通过 Mybatis 自动填充记录的创建时间和更新时间
mybatis
程序员张32 天前
SQL分析与打印-p6spy组件
spring boot·sql·mybatis·mybatisplus·p6spy
喜欢敲代码的程序员3 天前
SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:项目搭建(一)
spring boot·mysql·elementui·vue·mybatis