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);
    }
}

最后自行进行测试就好

相关推荐
简色7 小时前
题库批量(文件)导入的全链路优化实践
java·数据库·mysql·mybatis·java-rabbitmq
lunzi_fly11 小时前
【源码解读之 Mybatis】【核心篇】--第5篇:Executor执行器体系详解
mybatis
韩立学长17 小时前
【开题答辩实录分享】以《走失人口系统档案的设计与实现》为例进行答辩实录分享
mysql·mybatis·springboot
Flash Dog21 小时前
【MyBatis】——执行过程
java·mybatis
ss2733 天前
手写MyBatis第85弹:组合模式在SqlNode设计中的精妙应用
mybatis
sniper_fandc3 天前
MybatisPlus和pagehelper分页冲突—关于jsqlparser、pagehelper、MybatisPlus三者的版本兼容问题
mybatis·mybatisplus
上官浩仁4 天前
springboot3 mybatisplus 数据库操作入门与实战
spring boot·mybatis·db
weixin_419658314 天前
MyBatis 进阶
mybatis
祈祷苍天赐我java之术5 天前
Redis 热点数据与冷数据解析
java·redis·mybatis