Mybatis-Plus快速入门

依赖

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

<!--Mybatis-Plus-->
<dependency>
    <groupId>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&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true&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异常。

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值