MyBatis 简称 (MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
Mybatis官网:https://baomidou.com/pages/226c21/
快速开始
1. 在navicat,下建一个数据库,在数据库下执行.
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
2. 执行相应的sql代码
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
`
3.创建一个空的 Spring Boot 工程.
添加依赖pom.xml
使用的版本jdk1.8+springboot2.6.7+mybatis-plus3.5.1+mysql-connector5.1.38****
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
application.properties配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=sasa
ideal下载MybatisX插件再重启
idea连接DataBase
1。点击user表下MybatisX-Generator
2.basePackge:会在java包下生成你自定义的com.lyj.demo包
basePath:生成路径在java下
relative Package:生成实体类pojo包名
3.生成的效果图如下
4.配置user类
@TableId
private Long id;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface TableId {
/**
* 字段名(该值可无)
*/
String value() default "";
/**
* 主键类型
* {@link IdType}
*/
IdType type() default IdType.NONE;
}
现在 default IdType.NONE;主键默认为none
配置id 字段type =IdType.ASSIGN_ID使用是雪花算法
/**
* 主键ID
* IdType.ASSIGN_ID:**主键类型为number或string**
*/
@TableId(type =IdType.ASSIGN_ID )
private Long id;
**
把mapper下UserMapper.xml和UserMapper接口放在一起
@MapperScan(“com.lyj.demo.mapper”)
springboot扫描mapper包
@MapperScan("com.lyj.demo.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
现在可以在test目录下开始测试CRUD**
1.基础查询
2.基础添加
id:1519217781810864129(Long)
雪花算法生成的19字符的id
3.基础修改
4.基础删除