當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot整合Mybatis-plus实现增删查改
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot整合Mybatis-plus实现增删查改
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
今天給大家分享一下SpringBoot整合Mybatis-plus的增刪查改案例。
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>mybatis-plus-samples</artifactId><groupId>com.baomidou.mybaitsplus</groupId><version>0.0.1-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>mybatis-plus-sample-crud</artifactId><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><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId></dependency><dependency><groupId>p6spy</groupId><artifactId>p6spy</artifactId><version>3.8.1</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>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;/*** <p>* 用戶實體對應(yīng)表 user* </p>** @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;/*** <p>* MP 支持不需要 UserMapper.xml 這個模塊演示內(nèi)置 CRUD 咱們就不要 XML 部分了* </p>** @author hubin* @since 2018-08-11*/ public interface UserMapper extends BaseMapper<User> {}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, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');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.P6SpyDriverschema: classpath:db/schema-h2.sqldata: classpath:db/data-h2.sqlurl: jdbc:p6spy:h2:mem:testusername: rootpassword: 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 # 使用日志系統(tǒng)記錄 sql #appender=com.p6spy.engine.spy.appender.Slf4JLogger # 設(shè)置 p6spy driver 代理 deregisterdrivers=true # 取消JDBC URL前綴 useprefix=true # 配置記錄 Log 例外,可去掉的結(jié)果集有error,info,batch,debug,statement,commit,rollback,result,resultset. excludecategories=info,debug,result,batch,resultset # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 實際驅(qū)動可多個 #driverlist=org.h2.Driver # 是否開啟慢SQL記錄 outagedetection=true # 慢SQL記錄標準 2 秒 outagedetectioninterval=2SimpleTest.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;/*** <p>* 內(nèi)置 CRUD 演示* </p>** @author hubin* @since 2018-08-11*/ @RunWith(SpringRunner.class) @SpringBootTest public class SampleTest {@Resourceprivate UserMapper mapper;@Testpublic void aInsert() {User user = new User();user.setName("小羊");user.setAge(3);user.setEmail("abc@mp.com");assertThat(mapper.insert(user)).isGreaterThan(0);// 成功直接拿會寫的 IDassertThat(user.getId()).isNotNull();}@Testpublic void bDelete() {assertThat(mapper.deleteById(3L)).isGreaterThan(0);assertThat(mapper.delete(new QueryWrapper<User>().lambda().eq(User::getName, "Sandy"))).isGreaterThan(0);}@Testpublic void cUpdate() {assertThat(mapper.updateById(new User().setId(1L).setEmail("ab@c.c"))).isGreaterThan(0);assertThat(mapper.update(new User().setName("mp"),Wrappers.<User>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.<User>lambdaUpdate().set(User::getEmail, null).eq(User::getId, 2));assertThat(mapper.selectById(1).getEmail()).isEqualTo("ab@c.c");user = mapper.selectById(2);assertThat(user.getEmail()).isNull();assertThat(user.getName()).isEqualTo("mp");mapper.update(new User().setEmail("miemie@baomidou.com"),new QueryWrapper<User>().lambda().eq(User::getId, 2));user = mapper.selectById(2);assertThat(user.getEmail()).isEqualTo("miemie@baomidou.com");mapper.update(new User().setEmail("miemie2@baomidou.com"),Wrappers.<User>lambdaUpdate().set(User::getAge, null).eq(User::getId, 2));user = mapper.selectById(2);assertThat(user.getEmail()).isEqualTo("miemie2@baomidou.com");assertThat(user.getAge()).isNull();}@Testpublic void dSelect() {mapper.insert(new User().setId(10086L).setName("miemie").setEmail("miemie@baomidou.com").setAge(3));assertThat(mapper.selectById(10086L).getEmail()).isEqualTo("miemie@baomidou.com");User user = mapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, 10086));assertThat(user.getName()).isEqualTo("miemie");assertThat(user.getAge()).isEqualTo(3);mapper.selectList(Wrappers.<User>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<User>().select("id","name")).forEach(x -> {assertThat(x.getId()).isNotNull();assertThat(x.getEmail()).isNull();assertThat(x.getName()).isNotNull();assertThat(x.getAge()).isNull();});}@Testpublic void orderBy() {List<User> users = mapper.selectList(Wrappers.<User>query().orderByAsc("age"));assertThat(users).isNotEmpty();}@Testpublic void selectMaps() {List<Map<String, Object>> mapList = mapper.selectMaps(Wrappers.<User>query().orderByAsc("age"));assertThat(mapList).isNotEmpty();assertThat(mapList.get(0)).isNotEmpty();System.out.println(mapList.get(0));}@Testpublic void selectMapsPage() {IPage<Map<String, Object>> page = mapper.selectMapsPage(new Page<>(1, 5), Wrappers.<User>query().orderByAsc("age"));assertThat(page).isNotNull();assertThat(page.getRecords()).isNotEmpty();assertThat(page.getRecords().get(0)).isNotEmpty();System.out.println(page.getRecords().get(0));}@Testpublic void orderByLambda() {List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge));assertThat(users).isNotEmpty();}@Testpublic void testSelectMaxId() {QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.select("max(id) as id");User user = mapper.selectOne(wrapper);System.out.println("maxId=" + user.getId());List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByDesc(User::getId));Assert.assertEquals(user.getId().longValue(), users.get(0).getId().longValue());} }以上就是Mybatis-Plus的簡單的增刪查改。
部分內(nèi)容來自網(wǎng)絡(luò),有問題可以在下面評論,技術(shù)問題可以私聊我。
QQ技術(shù)交流群:213365178
轉(zhuǎn)載于:https://www.cnblogs.com/c1024/p/11012019.html
總結(jié)
以上是生活随笔為你收集整理的SpringBoot整合Mybatis-plus实现增删查改的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PMBOK第六版学习笔记
- 下一篇: 嵌入式c学习第一步:dev cpp编译器