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

最后自行进行测试就好

相关推荐
记忆不曾留3 小时前
Mybatis 源码解读-SqlSession 会话源码和Executor SQL操作执行器源码
mybatis·二级缓存·sqlsession会话·executor执行器·一级缓存localcache
昵称为空C1 天前
SpringBoot 实现DataSource接口实现多租户数据源切换方案
后端·mybatis
isyangli_blog2 天前
(2-10-1)MyBatis的基础与基本使用
java·开发语言·mybatis
_码农121382 天前
Mybatis简单练习注解sql和配置文件sql+注解形式加载+配置文件加载
mybatis
期待のcode2 天前
Maven
java·spring·maven·mybatis
独泪了无痕2 天前
一文搞懂MyBatis中的TypeHandler
数据库·后端·mybatis
Easocen2 天前
Mybatis学习笔记(十)
mybatis
千睢3 天前
Mybatis实现页面增删改查
mybatis
Warren983 天前
Java后端面试题(含Dubbo、MQ、分布式、并发、算法)
java·开发语言·分布式·学习·算法·mybatis·dubbo
羊锦磊3 天前
[ Mybatis 多表关联查询 ] resultMap
java·开发语言·数据库·mysql·mybatis