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

最后自行进行测试就好

相关推荐
代码的余温2 小时前
MyBatis集成Logback日志全攻略
java·tomcat·mybatis·logback
sniper_fandc8 小时前
SpringBoot系列—MyBatis(xml使用)
java·spring boot·mybatis
Charlie__ZS9 小时前
若依框架去掉Redis
java·redis·mybatis
N维世界2 天前
Mybatis-XML映射文件
xml·java·mybatis
慧一居士2 天前
MyBatis-Plus的完整使用示例,完整使用示例手册
mybatis
艺杯羹2 天前
MyBatis之核心对象与工作流程及SqlSession操作
java·mybatis
天天摸鱼的java工程师3 天前
MyBatis Plus 的实用技巧:从业务场景到代码实现
java·后端·mybatis
wuxuanok3 天前
Web后端开发-Mybatis
java·开发语言·笔记·学习·mybatis
netyeaxi3 天前
Java:使用spring-boot + mybatis如何打印SQL日志?
java·spring·mybatis
小七mod3 天前
【MyBatis】MyBatis与Spring和Spring Boot整合原理
spring boot·spring·mybatis