MyBatis-Plus——增删查改
開發環境
IDEA
JDK:1.8
Spring Boot:2.6.2
Maven:3.3.9
MySQL:8.0.23
數據庫準備
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 創建一個Spring Boot項目
初始化以下依賴
1.2 導入依賴
<!-- 數據庫驅動 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- mybatis-plus --><!-- mybatis-plus 是自己開發,并非官方的! --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.5</version></dependency>警告:引入 *MyBatis-Plus* 之后請不要再次引入 *MyBatis* 以及 *MyBatis-Spring*,以避免因版本差異導致的問題。
1.3 編寫配置文件
application.properties:
# mysql 5 驅動不同 com.mysql.jdbc.Driver # mysql 8 驅動不同com.mysql.cj.jdbc.Driver、需要增加時區的配置 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;// 在對應的Mapper上面繼承基本的類 BaseMapper @Repository// 代表持久層 public interface PersonMapper extends BaseMapper<Person> {// 所有的CRUD操作都已經編寫完成了// 我們不需要像以前的配置一大堆文件了! }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);}}結果:
這樣就搭建成功了!
配置日志
通過以上的輸出,我們并不知道其sql是怎么執行的,我們為了進一步探究其執行過程,我們在配置文件中加上日志配置。
application.properties:
# 配置日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl我們再次輸出:
通過這樣的日志輸出,我們就知道MyBatis-Plus到底幫我們執行了什么樣操作。
二、增刪查改操作
2.1 查詢操作
2.1.1 selectById
需求:查詢id為1的用戶信息。
代碼實現:
@Testvoid test() {Person person = personMapper.selectById(1);System.out.println(person);}2.1.2 selectList
需求:查詢全部的用戶信息。
代碼實現:
@Testvoid contextLoads() {List<Person> personList = personMapper.selectList(null);personList.forEach(System.out::println);}2.1.3 selectBatchIds
需求:查詢id為1和3的用戶信息。
代碼實現:
@Testvoid test2() {List<Person> personList = personMapper.selectBatchIds(Arrays.asList(1,3));personList.forEach(System.out::println);}2.1.4 selectByMap
需求:查詢name為yixin,并且年齡為18歲的用戶信息。
代碼實現:
@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
代碼實現:
@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);// 受影響的行數System.out.println(person);//可以發現,id會自動回填}結果:
數據庫插入的id的默認值為:全局的唯一id
2.2.2 自增Id
如果我們不想他每次都給我們隨機生成id,而是希望通過在原有id基礎上進行自增,那么我們可以這么操作。
第一步:設置數據庫主鍵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; }然后我們再進行多次插入,看看是否會進行自增操作。
可以發現,能夠成功的進行自增操作了!
對于每一個id,大家不用擔心會重復,因為其采用的是【雪花算法】生成的,可以保證id幾乎全球唯一!
雪花算法
snowflake是Twitter開源的分布式ID生成算法,結果是一個long型的ID。
其核心思想是:
使用41bit作為毫秒數,
10bit作為機器的ID(5個bit是數據中心,5個bit的機器ID),
12bit作為毫秒內的流水號(意味著每個節點在每毫秒可以產生 4096 個 ID),
最后還有一個符號位,永遠是0。
2.3 刪除操作
2.3.1 deleteById
需求:刪除id為5的用戶信息。
代碼實現:
@Testvoid test6() {int result=personMapper.deleteById(5L);System.out.println(result);// 受影響的行數}2.3.2 deleteByMap
需求:刪除姓名為 Sandy,并且年齡為21的用戶信息。
代碼實現:
@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);// 受影響的行數}2.4 更新操作
需求:將id為2的用戶的姓名更改為"一心同學"
代碼實現:
@Testvoid test5() {Person person =new Person();person.setId(2L);person.setName("一心同學");person.setAge(20);person.setEmail("test2@qq.com");int result=personMapper.updateById(person);System.out.println(result);// 受影響的行數}小結
以上就是對【MyBatis-Plus】基礎入門【增刪改查】的講解,看到以上對CRUD的操作是不是感覺特別清爽,而【MyBatis-Plus】的功能不僅僅如此,下一篇博客【一心同學】將會對其【注解】進行講解。
總結
以上是生活随笔為你收集整理的MyBatis-Plus——增删查改的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java实现 支付宝支付
- 下一篇: python精要(65)-类(2)-构造