今天给大家分享一下SpringBoot整合Mybatis-plus的增删查改案例。
pom.xml
mybatis-plus-samples
com.baomidou.mybaitsplus
0.0.1-SNAPSHOT
4.0.0
mybatis-plus-sample-crud
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
provided
com.h2database
h2
runtime
com.baomidou
mybatis-plus-boot-starter
p6spy
p6spy
3.8.1
org.springframework.boot
spring-boot-maven-plugin
MybatisPlusConfig.java
package com.baomidou.mybatisplus.samples.crud.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/**
* @author miemie
* @since 2018-08-10
*/
@Configuration
@MapperScan("com.baomidou.mybatisplus.samples.crud.mapper")
public class MybatisPlusConfig {
}
User.java
package com.baomidou.mybatisplus.samples.crud.entity;
import lombok.Data;
import lombok.experimental.Accessors;
/**
*
* 用户实体对应表 user
*
*
* @author hubin
* @since 2018-08-11
*/
@Data
@Accessors(chain = true)
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
UserMapper.java
package com.baomidou.mybatisplus.samples.crud.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.samples.crud.entity.User;
/**
*
* MP 支持不需要 UserMapper.xml 这个模块演示内置 CRUD 咱们就不要 XML 部分了
*
*
* @author hubin
* @since 2018-08-11
*/
public interface UserMapper extends BaseMapper {
}
CrudApplication.java
package com.baomidou.mybatisplus.samples.crud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
}
resources/db/data-h2.sql
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
resources/db/schema-h2.sql
DROP TABLE IF EXISTS user;
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)
);
application.yaml
# DataSource Config
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
schema: classpath:db/schema-h2.sql
data: classpath:db/data-h2.sql
url: jdbc:p6spy:h2:mem:test
username: root
password: test
# Logger Config
logging:
level:
com.baomidou.mybatisplus.samples: debug
# MyBatis-Plus 配置该演示无
spy.properties
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,batch,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
SimpleTest.java
package com.baomidou.mybatisplus.samples.crud;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.samples.crud.entity.User;
import com.baomidou.mybatisplus.samples.crud.mapper.UserMapper;
/**
*
* 内置 CRUD 演示
*
*
* @author hubin
* @since 2018-08-11
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {
@Resource
private UserMapper mapper;
@Test
public void aInsert() {
User user = new User();
user.setName("小羊");
user.setAge(3);
user.setEmail("[email protected]");
assertThat(mapper.insert(user)).isGreaterThan(0);
// 成功直接拿会写的 ID
assertThat(user.getId()).isNotNull();
}
@Test
public void bDelete() {
assertThat(mapper.deleteById(3L)).isGreaterThan(0);
assertThat(mapper.delete(new QueryWrapper()
.lambda().eq(User::getName, "Sandy"))).isGreaterThan(0);
}
@Test
public void cUpdate() {
assertThat(mapper.updateById(new User().setId(1L).setEmail("[email protected]"))).isGreaterThan(0);
assertThat(
mapper.update(
new User().setName("mp"),
Wrappers.lambdaUpdate()
.set(User::getAge, 3)
.eq(User::getId, 2)
)
).isGreaterThan(0);
User user = mapper.selectById(2);
assertThat(user.getAge()).isEqualTo(3);
assertThat(user.getName()).isEqualTo("mp");
mapper.update(
null,
Wrappers.lambdaUpdate().set(User::getEmail, null).eq(User::getId, 2)
);
assertThat(mapper.selectById(1).getEmail()).isEqualTo("[email protected]");
user = mapper.selectById(2);
assertThat(user.getEmail()).isNull();
assertThat(user.getName()).isEqualTo("mp");
mapper.update(
new User().setEmail("[email protected]"),
new QueryWrapper()
.lambda().eq(User::getId, 2)
);
user = mapper.selectById(2);
assertThat(user.getEmail()).isEqualTo("[email protected]");
mapper.update(
new User().setEmail("[email protected]"),
Wrappers.lambdaUpdate()
.set(User::getAge, null)
.eq(User::getId, 2)
);
user = mapper.selectById(2);
assertThat(user.getEmail()).isEqualTo("[email protected]");
assertThat(user.getAge()).isNull();
}
@Test
public void dSelect() {
mapper.insert(
new User().setId(10086L)
.setName("miemie")
.setEmail("[email protected]")
.setAge(3));
assertThat(mapper.selectById(10086L).getEmail()).isEqualTo("[email protected]");
User user = mapper.selectOne(new QueryWrapper().lambda().eq(User::getId, 10086));
assertThat(user.getName()).isEqualTo("miemie");
assertThat(user.getAge()).isEqualTo(3);
mapper.selectList(Wrappers.lambdaQuery().select(User::getId))
.forEach(x -> {
assertThat(x.getId()).isNotNull();
assertThat(x.getEmail()).isNull();
assertThat(x.getName()).isNull();
assertThat(x.getAge()).isNull();
});
mapper.selectList(new QueryWrapper().select("id","name"))
.forEach(x -> {
assertThat(x.getId()).isNotNull();
assertThat(x.getEmail()).isNull();
assertThat(x.getName()).isNotNull();
assertThat(x.getAge()).isNull();
});
}
@Test
public void orderBy() {
List users = mapper.selectList(Wrappers.query().orderByAsc("age"));
assertThat(users).isNotEmpty();
}
@Test
public void selectMaps() {
List
以上就是Mybatis-Plus的简单的增删查改。
部分内容来自网络,有问题可以在下面评论,技术问题可以私聊我。
QQ技术交流群:213365178