一.创建数据表
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)
);
#插入数据
INSERT INTO user (id, name, age, email) VALUES
(1, 'zhangsan', 18, 'zhangsan@baomidou.com'),
(2, 'lisi', 20, 'lisi@baomidou.com'),
(3, 'wangwu', 28, 'wangwu@baomidou.com'),
(4, 'zhaoliu', 21, 'zhaoliu@baomidou.com'),
(5, 'zhao', 24, 'zhao@baomidou.com');
二.创建工程导入依赖
①打开IDEA-file-new-project;选择spring initializr快速创建一个springboot工程;
②设置包名和项目名,选择JDK1.8,版本随便选一个;
③项目创建后,pom.xml中把版本改为2.2.6.RELEASE
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
导入依赖:
<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>
<!--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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
三.创建实体类和mapper接口和配置application.properties
①创建bean
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
②创建mapper继承BaseMapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
③在引导类上添加扫描mapper包名
@MapperScan("你的mapper包名全路径")
④配置application.properties
#连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
#日志打印
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
四.测试
//1.测试查询
@Test
public void testSelect() {
List<User> users = userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
//2.测试插入
@Test
public void testSave() {
User user = new User();
// user.setId(8L);不设置id,有MP已经设置的雪花算法自动生产19位id
user.setAge(23);
user.setEmail("123@qq.com");
user.setName("shu");
userMapper.insert(user);
}
//3.测试修改
@Test
public void testUpdate() {
//修改用户要根据id查询;id为数据库生成的id
User user =userMapper.selectById(1381528503537979393L);
// user.setId(8L);
user.setName("shum");
userMapper.updateById(user);
}
//4.测试物理删除
@Test
public void testDelete() {
userMapper.deleteById(1381528503537979393L);
}