依赖
导入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异常。