MyBatis-Plus——增删查改
開發(fā)環(huán)境
IDEA
JDK:1.8
Spring Boot:2.6.2
Maven:3.3.9
MySQL:8.0.23
數(shù)據(jù)庫準(zhǔn)備
CREATE DATABASE mybatis_plus_db;DROP TABLE IF EXISTS person; CREATE TABLE person(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));INSERT INTO person (id, name, age, email) VALUES (1, 'yixin', 18, 'test1@qq.com'), (2, 'Jack', 20, 'test2@qq.com'), (3, 'Tom', 28, 'test3@qq.com'), (4, 'Sandy', 21, 'test4@qq.com'), (5, 'Billie', 24, 'test5@qq.com');一、項目搭建
1.1 創(chuàng)建一個Spring Boot項目
初始化以下依賴
1.2 導(dǎo)入依賴
<!-- 數(shù)據(jù)庫驅(qū)動 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- mybatis-plus --><!-- mybatis-plus 是自己開發(fā),并非官方的! --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.5</version></dependency>警告:引入 *MyBatis-Plus* 之后請不要再次引入 *MyBatis* 以及 *MyBatis-Spring*,以避免因版本差異導(dǎo)致的問題。
1.3 編寫配置文件
application.properties:
# mysql 5 驅(qū)動不同 com.mysql.jdbc.Driver # mysql 8 驅(qū)動不同com.mysql.cj.jdbc.Driver、需要增加時區(qū)的配置 serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver1.4 建立目錄
1.5 編寫實體類
實體類Person:
package com.yixin.mybatis_plus.pojo;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Person {private Long id;private String name;private Integer age;private String email; }1.6 編寫接口
PersonMapper接口:
package com.yixin.mybatis_plus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yixin.mybatis_plus.pojo.Person; import org.springframework.stereotype.Repository;// 在對應(yīng)的Mapper上面繼承基本的類 BaseMapper @Repository// 代表持久層 public interface PersonMapper extends BaseMapper<Person> {// 所有的CRUD操作都已經(jīng)編寫完成了// 我們不需要像以前的配置一大堆文件了! }1.7 主啟動類添加注解掃描
注意:在主啟動類上去掃描我們的mapper包下的所有接口
package com.yixin.mybatis_plus;import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan("com.yixin.mybatis_plus.mapper") @SpringBootApplication public class MybatisPlusApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusApplication.class, args);}}1.8 測試
package com.yixin.mybatis_plus;import com.yixin.mybatis_plus.mapper.PersonMapper; import com.yixin.mybatis_plus.pojo.Person; 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 MybatisPlusApplicationTests {@Autowiredprivate PersonMapper personMapper;@Testvoid contextLoads() {List<Person> personList = personMapper.selectList(null);personList.forEach(System.out::println);}}結(jié)果:
這樣就搭建成功了!
配置日志
通過以上的輸出,我們并不知道其sql是怎么執(zhí)行的,我們?yōu)榱诉M(jìn)一步探究其執(zhí)行過程,我們在配置文件中加上日志配置。
application.properties:
# 配置日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl我們再次輸出:
通過這樣的日志輸出,我們就知道MyBatis-Plus到底幫我們執(zhí)行了什么樣操作。
二、增刪查改操作
2.1 查詢操作
2.1.1 selectById
需求:查詢id為1的用戶信息。
代碼實現(xiàn):
@Testvoid test() {Person person = personMapper.selectById(1);System.out.println(person);}2.1.2 selectList
需求:查詢?nèi)康挠脩粜畔ⅰ?/strong>
代碼實現(xiàn):
@Testvoid contextLoads() {List<Person> personList = personMapper.selectList(null);personList.forEach(System.out::println);}2.1.3 selectBatchIds
需求:查詢id為1和3的用戶信息。
代碼實現(xiàn):
@Testvoid test2() {List<Person> personList = personMapper.selectBatchIds(Arrays.asList(1,3));personList.forEach(System.out::println);}2.1.4 selectByMap
需求:查詢name為yixin,并且年齡為18歲的用戶信息。
代碼實現(xiàn):
@Testvoid test3() {HashMap<String ,Object> map=new HashMap<>();map.put("name","yixin");map.put("age",18);List<Person> personList = personMapper.selectByMap(map);personList.forEach(System.out::println);}我們來看一下這條語句,它是如何生成的:
通過這樣日志的查看,是不是就感覺馬上就理解了!
2.2 增加操作
2.2.1 insert
需求:插入用戶的信息如下
name:張三
age:21
email:test6@qq.com
代碼實現(xiàn):
@Testvoid test4() {// 我們沒有自定義id,它會幫我們自動生成idPerson person =new Person();person.setName("張三");person.setAge(21);person.setEmail("test6@qq.com");int result=personMapper.insert(person);System.out.println(result);// 受影響的行數(shù)System.out.println(person);//可以發(fā)現(xiàn),id會自動回填}結(jié)果:
數(shù)據(jù)庫插入的id的默認(rèn)值為:全局的唯一id
2.2.2 自增Id
如果我們不想他每次都給我們隨機(jī)生成id,而是希望通過在原有id基礎(chǔ)上進(jìn)行自增,那么我們可以這么操作。
第一步:設(shè)置數(shù)據(jù)庫主鍵id為自增。
第二步:在實體類的id屬性增加注解@TableId(type = IdType.AUTO)
package com.yixin.mybatis_plus.pojo;import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Person {@TableId(type = IdType.AUTO)private Long id;private String name;private Integer age;private String email; }然后我們再進(jìn)行多次插入,看看是否會進(jìn)行自增操作。
可以發(fā)現(xiàn),能夠成功的進(jìn)行自增操作了!
對于每一個id,大家不用擔(dān)心會重復(fù),因為其采用的是【雪花算法】生成的,可以保證id幾乎全球唯一!
雪花算法
snowflake是Twitter開源的分布式ID生成算法,結(jié)果是一個long型的ID。
其核心思想是:
使用41bit作為毫秒數(shù),
10bit作為機(jī)器的ID(5個bit是數(shù)據(jù)中心,5個bit的機(jī)器ID),
12bit作為毫秒內(nèi)的流水號(意味著每個節(jié)點在每毫秒可以產(chǎn)生 4096 個 ID),
最后還有一個符號位,永遠(yuǎn)是0。
2.3 刪除操作
2.3.1 deleteById
需求:刪除id為5的用戶信息。
代碼實現(xiàn):
@Testvoid test6() {int result=personMapper.deleteById(5L);System.out.println(result);// 受影響的行數(shù)}2.3.2 deleteByMap
需求:刪除姓名為 Sandy,并且年齡為21的用戶信息。
代碼實現(xiàn):
@Testvoid test7() {HashMap<String, Object> map=new HashMap<>();map.put("name","Sandy");map.put("age",21);int result=personMapper.deleteByMap(map);System.out.println(result);// 受影響的行數(shù)}2.4 更新操作
需求:將id為2的用戶的姓名更改為"一心同學(xué)"
代碼實現(xiàn):
@Testvoid test5() {Person person =new Person();person.setId(2L);person.setName("一心同學(xué)");person.setAge(20);person.setEmail("test2@qq.com");int result=personMapper.updateById(person);System.out.println(result);// 受影響的行數(shù)}小結(jié)
以上就是對【MyBatis-Plus】基礎(chǔ)入門【增刪改查】的講解,看到以上對CRUD的操作是不是感覺特別清爽,而【MyBatis-Plus】的功能不僅僅如此,下一篇博客【一心同學(xué)】將會對其【注解】進(jìn)行講解。
總結(jié)
以上是生活随笔為你收集整理的MyBatis-Plus——增删查改的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java实现 支付宝支付
- 下一篇: 程序员法律考试(7)-民法(4)