MP实战系列(十一)之封装方法详解(续一)
之前寫(xiě)的封裝方法詳解,比較簡(jiǎn)要。
今天我主要講增加和刪除及其修改。查的話(huà)得單獨(dú)再詳講。
增刪改查,無(wú)論是Java或者C#等等,凡是對(duì)數(shù)據(jù)庫(kù)操作的都離不開(kāi)這四個(gè)。
一、增加方法講解
MyBatis Plus很好的將增加的方法進(jìn)行封裝。
而且它封裝的這個(gè)比原來(lái)的MyBatis要靈活的多。
比如下面代碼:
UserEntity u = new UserEntity();u .setLogo(0);u .setCreateTime(DateUtils.getDateTime());u .setEmail("test@231.com");u.setPassword("123456");u.setSex("1");u.setUsername("test001");int line = ud.insert(u); System.out.println(line);調(diào)用就是對(duì)應(yīng)BaseMapper里面的該方法:
/*** <p>* 插入一條記錄* </p>** @param entity 實(shí)體對(duì)象* @return int*/Integer insert(T entity);你可以指定需要在數(shù)據(jù)表中插入的數(shù)據(jù)。至于主鍵有四種策略:
主鍵策略源碼:
/*** Copyright (c) 2011-2020, hubin (jobob@qq.com).* <p>* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at* <p>* http://www.apache.org/licenses/LICENSE-2.0* <p>* Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/ package com.baomidou.mybatisplus.enums;/*** <p>* 生成ID類(lèi)型枚舉類(lèi)* </p>** @author hubin* @Date 2015-11-10*/ public enum IdType {AUTO(0, "數(shù)據(jù)庫(kù)ID自增"), INPUT(1, "用戶(hù)輸入ID"),/* 以下2種類(lèi)型、只有當(dāng)插入對(duì)象ID 為空,才自動(dòng)填充。 */ID_WORKER(2, "全局唯一ID"), UUID(3, "全局唯一ID"), NONE(4, "該類(lèi)型為未設(shè)置主鍵類(lèi)型");/*** 主鍵*/private final int key;/*** 描述*/private final String desc;IdType(final int key, final String desc) {this.key = key;this.desc = desc;}/*** <p>* 主鍵策略 (默認(rèn) ID_WORKER)* </p>** @param idType ID 策略類(lèi)型* @return*/public static IdType getIdType(int idType) {IdType[] its = IdType.values();for (IdType it : its) {if (it.getKey() == idType) {return it;}}return ID_WORKER;}public int getKey() {return this.key;}public String getDesc() {return this.desc;}}
這四種簡(jiǎn)單的說(shuō),根據(jù)數(shù)據(jù)表中的主鍵而定,如果你的主鍵是int或者tinyint類(lèi)型,可以使用自增策略,如果是varchar類(lèi)型可以使用UUID或者自定義以某種方式進(jìn)行主鍵生成,通常自定義的話(huà),需要在調(diào)用增加方法的時(shí)候進(jìn)行setId(),setId()里面可以填寫(xiě),也可以調(diào)用某個(gè)工具類(lèi)隨機(jī)生成等。
UserEntity u = new UserEntity();u .setLogo(0);u .setCreateTime(DateUtils.getDateTime());u .setEmail("test@123.com");u.setPassword("123456");u.setSex("1");u.setUsername("test003");int lines = ud.insertAllColumn(u);System.out.println(lines);?
這里的代碼和第一段代碼基本是一樣的除了方法名不一樣而已,方法的作用都是增加,MyBatis Plus開(kāi)發(fā)者之所以這樣起名,我認(rèn)為應(yīng)該是有個(gè)區(qū)分,方法如其名,insertAllColumn意為插入該表所有數(shù)據(jù),如果該表有十列,那么這一條數(shù)據(jù)也應(yīng)該包含十個(gè)列名,對(duì)應(yīng)Java中,也就是屬性名。
?
?
二、修改方法講解
修改中在實(shí)際開(kāi)發(fā),也應(yīng)用很多,基本可以說(shuō),對(duì)于龐大的業(yè)務(wù)系統(tǒng)而言,數(shù)據(jù)是不允許刪除的,頂多就是改改狀態(tài),假性刪除。對(duì)于數(shù)據(jù)為王的時(shí)代,數(shù)據(jù)就是經(jīng)濟(jì),數(shù)據(jù)就是發(fā)展。
于是誕生了一個(gè)叫大數(shù)據(jù)的玩意,幫助人們管理數(shù)據(jù),然后又誕生了一個(gè)職業(yè)叫數(shù)據(jù)分析師,通過(guò)分析數(shù)據(jù)得到某個(gè)結(jié)論,從而發(fā)掘某個(gè)市場(chǎng)。
修改的話(huà)與增加基本一致,不一致的就是一個(gè)在數(shù)據(jù)表中插入一條數(shù)據(jù),而修改,顧名思義,當(dāng)然是修改對(duì)應(yīng)的數(shù)據(jù)。
代碼如下:
UserEntity u = new UserEntity();u.setUserId(34);u .setLogo(0);u .setCreateTime(DateUtils.getDateTime());u .setEmail("test@123.com");u.setPassword("123456");u.setSex("2");u.setUsername("test003");int lines = ud.updateById(u);System.out.println(lines);updateById(),意思是根據(jù)主鍵進(jìn)行修改
相當(dāng)于MyBatis這樣的一條sql語(yǔ)句:udpate `user` set logo=#{logo} where userId=#{userId}
根據(jù)主鍵進(jìn)行修改。
如果不指定主鍵就無(wú)法完成修改業(yè)務(wù)。
源代碼如下:
/*** <p>* 根據(jù) ID 修改* </p>** @param entity 實(shí)體對(duì)象* @return int*/Integer updateById(@Param("et") T entity);updateAllColumnById()意思也是以主鍵為主,對(duì)所有的數(shù)據(jù)列進(jìn)行修改,當(dāng)然了,這里的所有是指符合主鍵的條件。主鍵唯一的嘛,當(dāng)然僅僅就是對(duì)該條數(shù)據(jù)進(jìn)行修改 UserEntity u = new UserEntity();u.setUserId(34);u .setLogo(0);u .setCreateTime(DateUtils.getDateTime());u .setEmail("test@231.com");u.setPassword("123456");u.setSex("2");u.setUsername("test003");int lines = ud.updateAllColumnById(u);System.out.println(lines);
源代碼如下:
/*** <p>* 根據(jù) ID 修改* </p>** @param entity 實(shí)體對(duì)象* @return int*/Integer updateAllColumnById(@Param("et") T entity);?
大家或許要問(wèn),我不想通過(guò)主鍵來(lái)修改數(shù)據(jù),我只想傳幾個(gè)對(duì)應(yīng)的參數(shù)來(lái)修改數(shù)據(jù),別擔(dān)心,MyBatis Plus這個(gè)也替你考慮了。
看演示代碼:
UserEntity u = new UserEntity();u.setUserId(34);u .setLogo(0);u .setCreateTime(DateUtils.getDateTime());u .setEmail("test@231.com");u.setPassword("123456");u.setSex("4");u.setUsername("test003");EntityWrapper<UserEntity> wrapper = new EntityWrapper<UserEntity>();wrapper.eq("user_id", 34);wrapper.eq("email", "test@323.com");int lines = ud.update(u, wrapper);System.out.println(lines);?
上述代碼本質(zhì)的sql就是 update 表名 set column=#{data1},column2=#{data2} where user_id=#{userId} and email=#{email}
記住wrapper.eq()對(duì)應(yīng)的參數(shù),一個(gè)是數(shù)據(jù)表中的列名,另外一個(gè)就是對(duì)應(yīng)的值。記得一定要填寫(xiě)正確的列名,否則就會(huì)修改失敗。
對(duì)于傳統(tǒng)的MyBatis而言,找不到列,會(huì)報(bào)sql錯(cuò)誤等異常信息。而MyBatis Plus就不會(huì)報(bào)。
這里我提醒一句,還是那句話(huà),單元測(cè)試很重要,首先在單元測(cè)試,測(cè)試通過(guò)了,多弄幾個(gè)常用條件測(cè)試,測(cè)試都沒(méi)問(wèn)題,再進(jìn)行ui層面的,也就是web開(kāi)發(fā)。
源代碼如下:
/*** <p>* 根據(jù) whereEntity 條件,更新記錄* </p>** @param entity 實(shí)體對(duì)象* @param wrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)* @return*/Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper);?
這里的Wrapper<T> wrapper非常靈活
只要是wrapper里面有的方法,都可以常用。
比如:
wrapper.between(column, val1, val2)wrapper.groupBy(columns) //對(duì)應(yīng)sql中分組wrapper.eq(column, params) //相當(dāng)于where條件wrapper.in(column, value) //sql中inwrapper.notIn(column, value) //sql中 not inwrapper.orderBy(columns, isAsc) //排序wrapper.exists(value) //相對(duì)于sql中exists查詢(xún)wrapper.notExists(value) //相當(dāng)于sql中not exists查詢(xún)wrapper.notBetween(column, val1, val2) //相當(dāng)于sql中在某個(gè)范圍內(nèi)使用的betweenwrapper.ge(column, params) //大于等于wrapper.le(column, params) //小于等于wrapper.like(column, value) //模糊查詢(xún)wrapper.having(sqlHaving, params) //條件過(guò)濾上述wrapper都可以用,前提是只要你有這個(gè)需求。
?
三、刪除方法講解
雖然之前強(qiáng)調(diào)過(guò),刪除在實(shí)際應(yīng)用中,用的少,這個(gè)少是指需求。關(guān)鍵是看業(yè)務(wù)。
比如博客方面,博客系統(tǒng)有一個(gè)叫回收站的地方,回收站里面都是一些作者刪除沒(méi)用的文章放置處,這個(gè)資源對(duì)于非盈利性組織而言,回收處的垃圾需要定時(shí)清理。
不然的話(huà),數(shù)據(jù)量大也一定增加會(huì)增加服務(wù)器壓力,數(shù)據(jù)庫(kù)也是服務(wù)器,名曰:數(shù)據(jù)服務(wù)器。
deleteById()?根據(jù)主鍵進(jìn)行刪除
代碼如下:
int lines = ud.deleteById(34);System.out.println(lines);源碼如下:
/*** <p>* 根據(jù) ID 刪除* </p>** @param id 主鍵ID* @return int*/Integer deleteById(Serializable id);?
deleteByMap()方法
源代碼如下:
/*** <p>* 根據(jù) columnMap 條件,刪除記錄* </p>** @param columnMap 表字段 map 對(duì)象* @return int*/Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);?
演示代碼如下:
Map<String,Object> map = new HashMap<String,Object>();map.put("username", "李四");int lines = ud.deleteByMap(map);System.out.println(lines);?
本質(zhì)相當(dāng)于 delete from table where username=#{username}
還可以繼續(xù)增加條件,對(duì)于Java代碼而言就是增加幾個(gè)put。
?
delete()方法
源代碼如下:
/*** <p>* 根據(jù) entity 條件,刪除記錄* </p>** @param wrapper 實(shí)體對(duì)象封裝操作類(lèi)(可以為 null)* @return int*/Integer delete(@Param("ew") Wrapper<T> wrapper);?
演示代碼如下:
EntityWrapper<UserEntity> wrapper = new EntityWrapper<UserEntity>();wrapper.eq("username", "王麻子");wrapper.eq("email", "123@qq.com");int lines = ud.delete(wrapper);System.out.println(lines);其實(shí)本質(zhì)上還是它
這個(gè)"它"指的是?delete from table where username=#{username} and email=#{email}
只不過(guò)put里面的鍵必須與#{username}一致否則會(huì)刪除失敗,而對(duì)于eq而言,對(duì)應(yīng)鍵必須和數(shù)據(jù)表中的列名,即column一致,否則刪除失敗。就無(wú)法達(dá)到刪除數(shù)據(jù)的目的。
?
deleteBatchIds()
批量刪除,在實(shí)際中用的也比較多,主要針對(duì)無(wú)用日志或者對(duì)于博客而言,用戶(hù)刪除聊天信息等,通常一個(gè)一個(gè)刪除麻煩,直接批量刪除即可。
源碼如下:
/*** <p>* 刪除(根據(jù)ID 批量刪除)* </p>** @param idList 主鍵ID列表* @return int*/Integer deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);?
在這里也得提提動(dòng)態(tài)sql
deleteBatchIds();
本質(zhì)上代碼相當(dāng)于這個(gè):
<delete id="batchDeleteUser">delete from table where column in (<foreach collection="idList" item="attribute" separator=",">#{id}</foreach>) </delete>不過(guò)要看清楚了,還是基于主鍵批量刪除。
?
總結(jié):
個(gè)人看來(lái),不管怎么樣,MyBatis還是基礎(chǔ),只有當(dāng)MyBatis用的非常熟練,那么對(duì)于MyBatis Plus可以融會(huì)貫通。
本質(zhì)上說(shuō),MyBatis Plus就是MyBatis。MyBatis Plus的創(chuàng)建者們也一再?gòu)?qiáng)調(diào)多,MyBatis Plus對(duì)于MyBatis而言只做增強(qiáng)不做改變。
所以說(shuō),用MyBatis Plus,其實(shí)相當(dāng)于還在用MyBatis,只不過(guò),我們不需要再重復(fù)性寫(xiě)大量sql,當(dāng)然了,這個(gè)不寫(xiě),并不是指什么都不寫(xiě),而是指像增刪改這類(lèi)的,我們完全可以不用自己寫(xiě),因?yàn)镸yBatis Plus,已經(jīng)將它們都封裝好了。而我們只需調(diào)用即可。
當(dāng)然了,對(duì)于一些復(fù)雜業(yè)務(wù),需要多表查的,我們只能通過(guò)自己手動(dòng)編寫(xiě)了。這樣也保留了MyBatis的靈活性。
?
轉(zhuǎn)載于:https://www.cnblogs.com/youcong/p/9310848.html
總結(jié)
以上是生活随笔為你收集整理的MP实战系列(十一)之封装方法详解(续一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python基础学习(五)第一次修改
- 下一篇: 第三篇:函数之对象