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

<!--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>

二、配置数据源

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

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

三、创建对应的类

实体类


/**
 * @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


/**
 * @author ning0
 * @date 2024/8/1 18:56
 * @description UserMapper
 **/

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

UserService注意需要继承IService

public interface UserService extends IService<UserEntity> {
    public UserEntity getUserById(Long id);
}

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


/**
 * @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);
    }
}

最后自行进行测试就好

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值