1.导入项目基本坐标
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--Druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.4</version>
</dependency>
2.在application.yml文件中配置数据源
#Driud数据源
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/xia
username: root
password: 123456
#开启id自动适应 如果你的id是自增必须配置
mybatis-plus:
global-config:
db-config:
table-prefix:
id-type: auto
3.创建数据库表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
4.创建实体pojo
//使用lombok @Data对实体自动封装
@Data
public class User {
private int id;
private String user;
private String password;
}
5.创建Mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pzh.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
//使用BaseMapper实现对mapper的自动实现
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
6.在SpringbootTest中测试
package com.pzh;
import com.pzh.mapper.UserMapper;
import com.pzh.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class SpringbootSsmpApplicationTests {
@Autowired
private UserMapper mapper;
@Test
void contextLoads() {
//id查询
User user = mapper.selectById(1);
System.out.println(user);
System.out.println("...............");
//查询所有
List<User> users = mapper.selectList(null);
System.out.println(users);
System.out.println("...............");
//添加操作
System.out.println("添加操作");
User userInsert=new User();
userInsert.setUser("grmx");
user.setUser("123");
int insert = mapper.insert(userInsert);
if (insert!=0){
System.out.println("insert操作成功");
}
System.out.println("...............");
//删除操作
int delete = mapper.deleteById(15);
if (delete!=0){
System.out.println("delete操作成功");
}
else System.out.println("delete操作失败");
}
}