本文介绍: Mybatis-Plus快速入门;注意要用SpringBoot2,目前的Mybatis-Plus最新版本好像不兼容SpringBoot3,会出现java.lang.IllegalStateException异常

依赖

导入Mybatis-Plus的依赖,并且将Mybatis的依赖注释掉,避免版本冲突

<!--Mybatis-Plus-->
<dependency&gt;
    <groupId&gt;com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.2</version>
</dependency>

yml配置文件

数据库连接配置没有变化,使用的是 8.0.34 版本

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false&amp;allowPublicKeyRetrieval=true&amp;useAffectedRows=true
    username: root
    password: 123456

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

数据库

create table if not exists student
(
    id          bigint auto_increment comment '主键id'
        primary key,
    name        varchar(8) not null comment '姓名',
    gender      int        not null comment '性别;1代表男,2代表女',
    age         int        not null comment '年龄',
    create_time datetime   not null comment '创建时间',
    update_time datetime   not null comment '更新时间',
    constraint id
        unique (id)
)
    comment '学生表';

insert into student (id, name, gender, age, create_time, update_time)
values (null, '艾伦', 1, 15, now(), now());

Student

注意这里实体类名称表名保持一致,后面可以注解解决名称不一致的问题

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private Long id;
    private String name;
    private Integer gender;
    private Integer age;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

StudentMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.pojo.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}

测试

@Autowired
private StudentMapper studentMapper;

@Test
public void test() {
    //查询所有学生
    List<Student> students = studentMapper.selectList(null);
    students.forEach(System.out::println);
}

注意要用SpringBoot2,目前的Mybatis-Plus最新版本好像不兼容SpringBoot3,会出现java.lang.IllegalStateException异常

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注