以下内容参考尚硅谷的https://www.bilibili.com/video/BV1y7411y7am视频
1.创建一个springboot项目
1.1 选择spring initializr
1.2 填写项目信息
1.3 什么也不选,点击next
1.4 什么也不动,点击finish
2.配置pom和连接数据库
2.1 修改版本springboot版本为
在实际开发中,经常使用发行已久的稳定的版本,而不是最新的版本
2.2 导入相关依赖
除了自带的springboot-starter和springboot-test外,只导入了mybatisplus、mysql和lombok三个依赖
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.3 连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
3.建立数据库
DROP TABLE IF EXISTS USER;
CREATE TABLE USER(
id BIGINT(20) NOT NULL COMMENT '主键',
NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
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');
ALTER TABLE USER ADD COLUMN version INT;
ALTER TABLE USER ENGINE=INNODB CHARSET=UTF8;
ALTER TABLE USER ADD COLUMN deleted TINYINT(1) DEFAULT 0;
4.建立实体类,mapper和测试
4.1 建立实体类
package com.nslt.mpdemo10101.entity;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
4.2 建立mapper
注意使用@Repository注解
package com.nslt.mpdemo10101.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nslt.mpdemo10101.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
4.3 @mapperscan
在启动类上添加@MapperScan注解
@MapperScan("com.nslt.mpdemo10101.mapper")
@SpringBootApplication
public class Mpdemo10101Application {
public static void main(String[] args) {
SpringApplication.run(Mpdemo10101Application.class, args);
}
}
4.4 测试
查询所有用户
@Autowired
private UserMapper userMapper;
@Test
public void selectAllUsers(){
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
运行结果如下