- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- MyBatis常用動(dòng)態(tài)sql大總結
相信大家沒(méi)用Mybatis之前,都碰到過(guò)各種條件判斷拼接SQL、需要去掉多余的逗號等痛苦,Mybatis中的動(dòng)態(tài)SQL能很好的解決上面說(shuō)的情況,可以很靈活的組裝SQL語(yǔ)句,從而提高開(kāi)發(fā)效率。
test中寫(xiě)判斷條件 參數直接paramN或者別名 特點(diǎn): 只要成立就拼接在Sql語(yǔ)句中,都成立就全部都拼接 注意: where子句中加上1=1來(lái)規避and的風(fēng)險
<select id="uid" resultType="UserEntity"> select * from UserEntity where 1=1 <if test="param1!=null and param1!=''"> and outno=#{param1} </if> <if test="param2!=null and param2!=''"> and inno=#{param2} </if> </select>
條件模糊查以及查詢(xún)時(shí)間段內數據
<select id="uid" resultType="UserEntity"> select * from UserEntity where 1=1 <if test="param1!=null and param1!=''"> and outno=#{param1} </if> <if test="param2!=null and param2!=''">and inno LIKE CONCAT('%',#{param2 },'%' ) </if> <if test="effectiveTime !=null and effectiveTime !=''"> and begin_time <= #{effectiveTime} //effectiveTime 是封的查詢(xún)條件類(lèi)的查詢(xún)字段 and end_time >= #{effectiveTime} //begin_time,end_time 對應數據庫字段。 </if> </select>
特點(diǎn):
會(huì )自動(dòng)地給Sql語(yǔ)句添加where關(guān)鍵字,并將第一個(gè)and去除。
<select id="uid" resultType="UserEntity"> select * from UserEntity <where> <if test="param1!=null and param1!=''"> and outno=#{param1} </if> <if test="param2!=null and param2!=''"> and inno=#{param2} </if> </where> </select>
特點(diǎn):
條件只要有一個(gè)成立,其他的就不會(huì )再判斷了。
如果沒(méi)有成立的條件則默認執行otherwise中的內容
<select id="uid" resultType="UserEntity"> select * from UserEntity <where> <choose> <when test="param1!=null and param1!=''"> and outno=#{param1} </when> <when test="param2!=null and param2!=''"> and inno=#{param2} </when> <otherwise> and 1=1 </otherwise> </choose> </where> </select>
產(chǎn)生一個(gè)set關(guān)鍵字,自動(dòng)去除最后一個(gè)逗號。
注意:
在判斷條件中最后保持有一個(gè)永遠成立的條件。避免sql錯誤。
<update id="uid"> update accountTable <set> <if test="aname!=null and aname!=''"> aname=#{aname}, </if> <if test="money !=null and money !=''"> money=#{money}, </if> <if test="ano !=null and ano !=''"> ano=#{ano}, </if> </set> where ano=#{ano} </update>
prefix:在trim的內容前添加指定的內容
prefixOverrides在trim的內容前去除指定的內容
suffix:在trim的內容后添加指定的內容
suffixOverrides:在trim的內容后去除指定的內容
注意:
先去除后添加
添加內容會(huì )默認添加一個(gè)空格。
<update id="upT" parameterType="account"> update account <trim prefix="$" prefixOverrides="" suffix="" suffixOverrides=""> <if test="ano !=null and ano !=''"> ano=#{ano}, </if> <if test="aname!=null and aname!=''"> aname=#{aname}, </if> <if test="money !=null and money !=''"> money=#{money}, </if> </trim> where ano=#{ano} </update>
name:參數名
value:表達式,注意字符串拼接按照變量方式進(jìn)行拼接
例如:
<bind name="money" value="'$'+money"/>
給參數重新賦值
<update id="upB" parameterType="account"> <bind name="money" value="money+100"/> update account <trim prefix="set" suffixOverrides=","> <if test="ano !=null and ano !=''"> ano=#{ano}, </if> <if test="aname!=null and aname!=''"> aname=#{aname}, </if> <if test="money !=null and money !=''"> money=#{money}, </if> </trim> where ano=#{ano} </update>
sql標簽:在外部聲明公用SQL語(yǔ)句
id
include標簽:引入聲明的公共SQL語(yǔ)句
refid:
優(yōu)點(diǎn):便于SQL的整體修改
缺點(diǎn):難于閱讀
<select id="selA" resultType="account"> select <include refid="mysql"></include> from account </select> <sql id="mysql"> ano,aname,apwd,money </sql>
構造IN條件語(yǔ)句時(shí)需要對集合進(jìn)行遍歷,這時(shí)候可以使用foreach元素。foreach會(huì )去掉多余","。若集合為空,則不會(huì )執行foreach元素中的操作,但此時(shí)會(huì )多出"in"關(guān)鍵字,報錯。
item:集合中的元素
index:元素所在集合的下標,迭代map時(shí),index是鍵
collection:集合的類(lèi)型,可選值list,array,除此之外還可以是@Param("name")、Map中的key、類(lèi)的成員變量 open、
close:在首、尾拼接的字符
separator:每個(gè)元素間的分隔符
注: foreach標簽支持List、Set、Map、Array等的遍歷
迭代數組或者List、Set集合時(shí),index是迭代次數,item是本次迭代獲取的元素;
迭代Map(或Map.Entry對象的集合)時(shí),index是鍵,item是值
collection屬性介紹
傳入單參數且是List時(shí),collection="list"
傳入單參數且是Array時(shí),collection="array"
傳入單參數且是Set時(shí),需使用@Param注解,同下
傳入單參數且使用@Param("name")時(shí),collection="name",即和@Param注解的value屬性值相同,此時(shí)list、array無(wú)效
傳入多參數且封裝成Map時(shí),如map.put("ids", Arrays.asList(1, 2)),此時(shí)collection="ids"
傳入多參數且封裝成類(lèi)時(shí),如User類(lèi)中有成員變量List roleIds,此時(shí)collection="roleIds";若User類(lèi)中有成員變量Role role,Role類(lèi)中有成員變量prilIds,此時(shí)collection="role.prilIds"
<select id="selF" parameterType="list" resultType="account"> select * from account where ano in <foreach collection="list" item="item" open="(" separator="," close=")"> #{item} </foreach> </select> <insert id="inF"> insert into log values <foreach collection="list" item="log" separator=","> (#{log.outno},#{log.inno},#{log.money}) </foreach> </insert>
批量修改的動(dòng)態(tài)sql
controller層
/** * 批量修改 */ @PutMapping("/aaa") @ApiOperation(value = "下架") public R aaa(@RequestBody Asa asa) { this.goodTestService.updateState(asa.getIds(),asa.getMsg()); return R.data("cg"); }
service
package com.troy.testa.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import com.troy.testa.dto.GoodTestDTO; import com.troy.testa.entity.GoodTest; import org.springframework.data.domain.Pageable; import java.util.List; /** * (GoodTest)表服務(wù)接口 * @author zhangh * @date 2021-03-21 15:31:34 */ public interface GoodTestService extends IService<GoodTest> { void updateState(String[] ids,String msg); }
serviceImp
@Override public void updateState(String[] ids,String msg) { baseMapper.updateState(ids,msg); }
dao
package com.troy.testa.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.troy.testa.dto.GoodTestDTO; import com.troy.testa.entity.GoodTest; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import com.baomidou.mybatisplus.core.metadata.IPage; import java.util.List; /** * (GoodTest)表數據庫訪(fǎng)問(wèn)層 * @author zhangh * @date 2021-03-21 15:31:34 */ @Mapper public interface GoodTestDao extends BaseMapper<GoodTest> { void updateState(@Param("ids") String[] ids,@Param("msg") String msg); }
xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.troy.testa.dao.GoodTestDao"> <update id="updateState"> <foreach collection="ids" item="item" index="index" separator=";"> UPDATE good_test SET good_state = 1,good_name=#{msg} WHERE id = #{item} </foreach> </update>
postman測試
表已批量修改
成功!
雖然可以用程序循環(huán)實(shí)現,但是用了動(dòng)態(tài)sql少去了不少工作量。
發(fā)中,經(jīng)常需要根據不同的條件動(dòng)態(tài)拼接SQL,并且還確??崭?、列名最后的逗號、多余的AND、OR條件等。在MyBatis中處理這種情況是比較方便容易的。
到此這篇關(guān)于MyBatis常用動(dòng)態(tài)sql的文章就介紹到這了,更多相關(guān)MyBatis動(dòng)態(tài)sql內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站