Spring boot使用Mybatis-Plus实现简单增删改查 SSMP

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操作失败");

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值