MyBatis常用動(dòng)態(tài)sql大總結(jié)
簡(jiǎn)介
相信大家沒(méi)用Mybatis之前,都碰到過(guò)各種條件判斷拼接SQL、需要去掉多余的逗號(hào)等痛苦,Mybatis中的動(dòng)態(tài)SQL能很好的解決上面說(shuō)的情況,可以很靈活的組裝SQL語(yǔ)句,從而提高開(kāi)發(fā)效率。
1、SQL的動(dòng)態(tài)拼接有哪些
- if標(biāo)簽
- where標(biāo)簽
- choose when otherwise標(biāo)簽
- set標(biāo)簽
- trim標(biāo)簽
- bind標(biāo)簽
- sql和include標(biāo)簽 foreach標(biāo)簽
2、if標(biāo)簽:
test中寫(xiě)判斷條件 參數(shù)直接paramN或者別名 特點(diǎn): 只要成立就拼接在Sql語(yǔ)句中,都成立就全部都拼接 注意: where子句中加上1=1來(lái)規(guī)避and的風(fēng)險(xiǎn)
<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>
條件模糊查以及查詢時(shí)間段內(nèi)數(shù)據(jù)
<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 是封的查詢條件類的查詢字段 and end_time >= #{effectiveTime} //begin_time,end_time 對(duì)應(yīng)數(shù)據(jù)庫(kù)字段。 </if> </select>
3、where標(biāo)簽:
特點(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>
4、choose when otherwise標(biāo)簽
特點(diǎn):
條件只要有一個(gè)成立,其他的就不會(huì)再判斷了。
如果沒(méi)有成立的條件則默認(rèn)執(zhí)行otherwise中的內(nèi)容
<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>
5、set標(biāo)簽:
產(chǎn)生一個(gè)set關(guān)鍵字,自動(dòng)去除最后一個(gè)逗號(hào)。
注意:
在判斷條件中最后保持有一個(gè)永遠(yuǎn)成立的條件。避免sql錯(cuò)誤。
<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>
6、trim標(biāo)簽:
prefix:在trim的內(nèi)容前添加指定的內(nèi)容
prefixOverrides在trim的內(nèi)容前去除指定的內(nèi)容
suffix:在trim的內(nèi)容后添加指定的內(nèi)容
suffixOverrides:在trim的內(nèi)容后去除指定的內(nèi)容
注意:
先去除后添加
添加內(nèi)容會(huì)默認(rèn)添加一個(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>
7、bind標(biāo)簽:
name:參數(shù)名
value:表達(dá)式,注意字符串拼接按照變量方式進(jìn)行拼接
例如:
<bind name="money" value="'$'+money"/>
給參數(shù)重新賦值
<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>
8、sql和include標(biāo)簽:
sql標(biāo)簽:在外部聲明公用SQL語(yǔ)句
id
include標(biāo)簽:引入聲明的公共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>
9、foreach標(biāo)簽:
構(gòu)造IN條件語(yǔ)句時(shí)需要對(duì)集合進(jìn)行遍歷,這時(shí)候可以使用foreach元素。foreach會(huì)去掉多余","。若集合為空,則不會(huì)執(zhí)行foreach元素中的操作,但此時(shí)會(huì)多出"in"關(guān)鍵字,報(bào)錯(cuò)。
item:集合中的元素
index:元素所在集合的下標(biāo),迭代map時(shí),index是鍵
collection:集合的類型,可選值list,array,除此之外還可以是@Param("name")、Map中的key、類的成員變量 open、
close:在首、尾拼接的字符
separator:每個(gè)元素間的分隔符
注: foreach標(biāo)簽支持List、Set、Map、Array等的遍歷
迭代數(shù)組或者List、Set集合時(shí),index是迭代次數(shù),item是本次迭代獲取的元素;
迭代Map(或Map.Entry對(duì)象的集合)時(shí),index是鍵,item是值
collection屬性介紹
傳入單參數(shù)且是List時(shí),collection="list"
傳入單參數(shù)且是Array時(shí),collection="array"
傳入單參數(shù)且是Set時(shí),需使用@Param注解,同下
傳入單參數(shù)且使用@Param("name")時(shí),collection="name",即和@Param注解的value屬性值相同,此時(shí)list、array無(wú)效
傳入多參數(shù)且封裝成Map時(shí),如map.put("ids", Arrays.asList(1, 2)),此時(shí)collection="ids"
傳入多參數(shù)且封裝成類時(shí),如User類中有成員變量List roleIds,此時(shí)collection="roleIds";若User類中有成員變量Role role,Role類中有成員變量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>
10、示例
批量修改的動(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)表數(shù)據(jù)庫(kù)訪問(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測(cè)試
表已批量修改
成功!
雖然可以用程序循環(huán)實(shí)現(xiàn),但是用了動(dòng)態(tài)sql少去了不少工作量。
總結(jié):
發(fā)中,經(jīng)常需要根據(jù)不同的條件動(dòng)態(tài)拼接SQL,并且還確??崭?、列名最后的逗號(hào)、多余的AND、OR條件等。在MyBatis中處理這種情況是比較方便容易的。
到此這篇關(guān)于MyBatis常用動(dòng)態(tài)sql的文章就介紹到這了,更多相關(guān)MyBatis動(dòng)態(tài)sql內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)微博后臺(tái)登錄發(fā)送微博
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)微博后臺(tái)登錄發(fā)送微博的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-07-07如何搭建一個(gè)完整的Java開(kāi)發(fā)環(huán)境
這篇文章主要教大家如何搭建一個(gè)完整的Java開(kāi)發(fā)環(huán)境,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11Java實(shí)現(xiàn)畫(huà)圖的詳細(xì)步驟(完整代碼)
今天給大家?guī)?lái)的是關(guān)于Java的相關(guān)知識(shí),文章圍繞著Java實(shí)現(xiàn)畫(huà)圖的詳細(xì)步驟展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06Java根據(jù)實(shí)體生成SQL數(shù)據(jù)庫(kù)表的示例代碼
這篇文章主要來(lái)和大家分享一個(gè)Java實(shí)現(xiàn)根據(jù)實(shí)體生成SQL數(shù)據(jù)庫(kù)表的代碼,文中的實(shí)現(xiàn)代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-07-07IDEA2023創(chuàng)建MavenWeb項(xiàng)目并搭建Servlet工程的全過(guò)程
Maven提供了大量不同類型的Archetype模板,通過(guò)它們可以幫助用戶快速的創(chuàng)建Java項(xiàng)目,這篇文章主要給大家介紹了關(guān)于IDEA2023創(chuàng)建MavenWeb項(xiàng)目并搭建Servlet工程的相關(guān)資料,需要的朋友可以參考下2023-10-10logback?EvaluatorFilter日志過(guò)濾器源碼解讀
這篇文章主要為大家介紹了logback?EvaluatorFilter日志過(guò)濾器源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11關(guān)于Idea卡在Resolving Maven dependencies的解決方案
本文詳細(xì)介紹了關(guān)于Idea卡在Resolving Maven dependencies的解決方案,文中通過(guò)圖文結(jié)合的形式給大家介紹的非常詳細(xì),對(duì)大家解決問(wèn)題有一定的幫助,需要的朋友可以參考下2024-02-02Java中數(shù)組轉(zhuǎn)List的三種方法與對(duì)比分析
這篇文章主要給大家介紹了關(guān)于Java中數(shù)組轉(zhuǎn)List的三種方法與對(duì)比分析的相關(guān)資料,分別介紹了最常見(jiàn)方式、數(shù)組轉(zhuǎn)為L(zhǎng)ist后,支持增刪改查的方式以及通過(guò)集合工具類Collections.addAll()方法,需要的朋友可以參考下2018-07-07Java編程二項(xiàng)分布的遞歸和非遞歸實(shí)現(xiàn)代碼實(shí)例
這篇文章主要介紹了Java編程二項(xiàng)分布的遞歸和非遞歸實(shí)現(xiàn)代碼實(shí)例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01