今天給你們分享一下SpringBoot整合Mybatis-plus的增刪查改案例。html
pom.xmljava
<?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.javaspring
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.javasql
package com.baomidou.mybatisplus.samples.crud.entity; import lombok.Data; import lombok.experimental.Accessors; /** * <p> * 用戶實體對應表 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.javaapache
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 這個模塊演示內置 CRUD 我們就不要 XML 部分了 * </p> * * @author hubin * @since 2018-08-11 */ public interface UserMapper extends BaseMapper<User> { }
CrudApplication.javaapi
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.sqlmybatis
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.yamlapp
# 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.propertiesmaven
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; /** * <p> * 內置 CRUD 演示 * </p> * * @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("abc@mp.com"); 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<User>() .lambda().eq(User::getName, "Sandy"))).isGreaterThan(0); } @Test public 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(); } @Test public 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(); }); } @Test public void orderBy() { List<User> users = mapper.selectList(Wrappers.<User>query().orderByAsc("age")); assertThat(users).isNotEmpty(); } @Test public 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)); } @Test public 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)); } @Test public void orderByLambda() { List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge)); assertThat(users).isNotEmpty(); } @Test public 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的簡單的增刪查改。
部份內容來自網絡,有問題能夠在下面評論,技術問題能夠私聊我。
QQ技術交流羣:213365178