首先创建一个springboot项目
添加mybatisPlus依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
在resources下创建db文件夹写数据库文件data.sql和scheme.sql
data.sql:
insert into shebei(id, name, label, price)
VALUES (2, '电磁炉', '超好用', 150),
(3, '宫保鸡丁', '贼香', 20),
(4, '键盘', '外设', 1000);
scheme.sql
DROP TABLE IF EXISTS shebei;
CREATE TABLE shebei
(
id int primary key,
name varchar(20),
label varchar(20),
price int
);
application.yml配置文件
#h2
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:testdb
username: sa
password: sa
sql:
init:
platform: h2
data-locations: classpath:db/data.sql
schema-locations: classpath:db/scheme.sql
mode: always
mybatis-plus:
type-aliases-package: com.strQeem.pojo
启动springboot项目
项目启动成功!
开始写代码:
实体类
package com.starQeem.pojo;
import lombok.Data;
@Data
public class shebei {
private Integer id;
private String name;
private String label;
private Integer price;
}
mapper层
shebeiMapper
package com.starQeem.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.starQeem.pojo.shebei;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface shebeiMapper extends BaseMapper<shebei> {
}
service层
shebeiService
package com.starQeem.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.starQeem.pojo.shebei;
public interface shebeiService extends IService<shebei> {
}
shebeiServiceImpl
package com.starQeem.service.Impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starQeem.mapper.shebeiMapper;
import com.starQeem.pojo.shebei;
import com.starQeem.service.shebeiService;
import org.springframework.stereotype.Service;
@Service
public class shebeiServiceImpl extends ServiceImpl<shebeiMapper, shebei> implements shebeiService {
}
测试类:
package com.starQeem;
import com.starQeem.pojo.shebei;
import com.starQeem.service.shebeiService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
class SpringbootMybatisPlusH2ApplicationTests {
@Resource
private shebeiService shebeiService;
@Test
@Order(3)
void query() {
shebeiService.list().forEach(System.out::println);
}
@Test
@Order(1)
void insert(){
shebei shebei = new shebei();
shebei.setId(1);
shebei.setName("喔哈牌显示器");
shebei.setLabel("显示器");
shebei.setPrice(500);
boolean success = shebeiService.save(shebei);
Assertions.assertTrue(success);
}
@Test
@Order(2)
void update(){
shebei shebei = new shebei();
shebei.setId(1);
shebei.setName("星星牌显示器");
boolean success = shebeiService.updateById(shebei);
Assertions.assertTrue(success);
}
@Test
@Order(4)
void delete(){
boolean success = shebeiService.removeById(4);
Assertions.assertTrue(success);
}
}
ok:
评论区