1. 程式人生 > >Mybatis——mapper.xml中常用的SQL相關標籤簡介

Mybatis——mapper.xml中常用的SQL相關標籤簡介

題外話:使用Map方式用於傳參,也是一種比較方便的方法

Map<String,Object> params = new HashMap<>(); 
params.put("name","a");
List<Product> ps2 = session.selectList("listProduct",params);

if標籤

用法:

<select id="listProduct" resultType="Product">
    select * from product_
    <if test="name!=null"
> where name like concat('%',#{name},'%') </if> </select>

where標籤

作用:
標籤會進行自動判斷
如果任何條件都不成立,那麼就在sql語句裡就不會出現where關鍵字(重點)
如果有任何條件成立,會自動去掉多出來的 and 或者 or。(就不需要我們追加1=1之類的入侵性程式碼了)
用法:

<select id="listProduct" resultType="Product">
    select * from product_
    <where
> <if test="name!=null"> and name like concat('%',#{name},'%') </if> <if test="price!=null and price!=0"> and price > #{price} </if> </where> </select>

set標籤

作用是:
與where標籤類似的,在update語句裡也會碰到多個欄位相關的問題。 在這種情況下,就可以使用set標籤。
其效果與where標籤類似,有資料的時候才進行設定。
用法:

<update id="updateProduct" parameterType="Product" >
    update product_
    <set>
        <if test="name != null">name=#{name},</if>
        <if test="price != null">price=#{price}</if> 
    </set>
     where id=#{id}   
</update>

trim標籤

作用是:
trim 用來定製想要的功能,比如where標籤就可以用
用法:

<select id="listProduct" resultType="Product">
    select *from product_
    <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test="name!=null">
            and name like concat('%',#{name},'%')
        </if>        
        <if test="price!=null and price!=0">
            and price > #{price}
        </if>
    </trim>      
</select>

<update id="updateProduct" parameterType="Product" >
    update product_
    <trim prefix="SET" suffixOverrides=",">
        <if test="name != null">name=#{name},</if>
        <if test="price != null">price=#{price}</if>   
    </trim>
     where id=#{id}   
</update>

trim 用來定製想要的功能,比如where標籤就可以用

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ... 
</trim>

來替換

set標籤就可以用

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

來替換
執行set標籤中的程式碼,其效果是一樣的。

choose when otherwise 標籤

作用是:
有任何任何條件符合,就進行條件查詢,
否則就只使用id>1這個條件(即前面的標籤都不符合條件)。
也就相當於if···········else

Mybatis裡面沒有else標籤,但是可以使用when otherwise標籤來達到這樣的效果。

用法:

<?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.how2java.pojo">
        <select id="listProduct" resultType="Product">
              SELECT * FROM product_
              <where>
                <choose>
                  <when test="name != null">
                    and name like concat('%',#{name},'%')
                  </when>          
                  <when test="price !=null and price != 0">
                    and price > #{price}
                  </when>                
                  <otherwise>
                    and id >1
                  </otherwise>
                </choose>
              </where>
        </select>
    </mapper>

foreach標籤

作用是:
foreach標籤通常用於in 這樣的語法裡。

用法(接收一個List集合引數):

<?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.how2java.pojo">
    <select id="listProduct" resultType="Product">
          SELECT * FROM product_
            WHERE ID in
                <foreach item="item" index="index" collection="list"
                    open="(" separator="," close=")">
                    #{item}
                </foreach>
    </select>
    </mapper>

bind標籤

bind標籤就像是再做一次字串拼接,網上也有說叫繫結,差不多意思,只是方便後續的使用。

用法:

<?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.how2java.pojo">

        <select id="listProduct" resultType="Product">
            <bind name="likename" value="'%' + name + '%'" />
            select * from   product_  where name like #{likename}
        </select>

    </mapper>

sql片段標籤

作用是:
通過該標籤可定義能複用的sql語句片段,在執行sql語句標籤中直接引用即可。
這樣既可以提高編碼效率,還能有效簡化程式碼,提高可讀性。
用法:

<!--定義sql片段-->
<sql id="orderAndItem">
    o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count
</sql>
<select id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">
    select
<!--引用sql片段-->
    <include refid="orderAndItem" />
    from ordertable o
    join orderitem i on o.orderitem_id = i.orderitem_id
    where o.order_id = #{orderId}
</select>

相關推薦

Mybatis——mapper.xml常用SQL相關標籤簡介

題外話:使用Map方式用於傳參,也是一種比較方便的方法 Map<String,Object> params = new HashMap<>(); params.put("

Mybatis mapper.xml常用標籤詳解

一、SQL語句標籤: <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "

MyBatis mapper.xmlSQL處理小於號與大於號 和小於等於號

class lsp adding style eight mybatis family height app 我們只需作如下替換即可避免上述的錯誤: < <= > >= & ‘ " &lt; &lt;= &

mybatis mapper.xml根據資料庫型別選擇對應SQL語句

1、spring-database.xml檔案中配置  <bean id="vendorProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">    &

MyBatis mapper.xmlSQL處理小於號與大於號

這種問題在xml處理sql的程式中經常需要我們來進行特殊處理。      其實很簡單,我們只需作如下替換即可避免上述的錯誤: < <= > >= & ' " &lt; &lt;= &gt; &gt

mapper.xml動態sql

-m 開始 集合屬性 參數 ack pub odin ids lose mabatis重點是通過標簽對sql靈活的組織,通過配置的方式完成輸入 輸出映射. 1.對mapper.xml中重復的sql抽取統一維護,以及foreach使用 UserMapperCustom.

[MyBatis] Mapper.xml的名稱空間及命名解析

Mapper.xml相關使用 名稱空間(Namespaces) 名稱空間(Namespaces) 在之前版本的MyBatis中是可選的,這樣容易引起混淆因此毫無益處。現在名稱空間則是必須的,且易於簡單地用更長的完完全限定名來隔離語句。 名稱空間使得你所見到的介面繫結成為可能,

XML配置dubbo相關標籤不能解析的問題

1、問題 Java工程中xml配置dubbo時提示如下問題: Multiple annotations found at this line: - cvc-complex-type.2.4.c: The matching wildcard is strict, but no d

mapper.xml常用配置

1:分頁列表     <sql id="sql_limit">         Limit #{startRow},#{pageSize}     </sql>     <sql id="order_by">         order

mybatis配置檔案mapper.xmltrim標籤的用法

在mapper.xml中對statement的定義,可以用<trim>來填充和隱藏sql語句。 <!--修改user的statement--><update id="updateUser" parameterType="user">update user <

mybatismapper.xmlselect標籤的parameterType屬性

SqlSession的selectList()與selcetOne()的第二個引數和selectMap()的第三個引數都表示方法的引數 程式碼如下 Flower flower = session.selectOne("com.bjsxt.mapper.Flowe

mybatismapper.xmlsql的用法

剛接觸的時候會有些摸不到頭腦,為此在網上搜索了一些相關的參考給自己作為借鑑 1.根據id查詢 select * from test_tb_info where 1=1 <if test="id != null and id !=''"> and info.id=#{id}

MyBatis Mapper.xml文件 $和#的區別

優先 註入 sql註入 jdb 防止 自動 || myba 由於 1.優先使用#{paramName,jdbcType=VARCHAR} 寫法,除了可以防止sql註入以外,它還能在參數裏含有單引號的時候自動轉義, 而${paramName}由於是類似於拼接sql的寫法,不具

Mybatismapper.xml<collection></collection>的用法

在mapper.xml檔案中,我們在使用collection時有兩種用法。這裡做一下簡單記錄: 1、直接將collection集合元素的屬性寫為collection的字標籤 如下: <resultMap type="com.space.shiro.bean.User" id="userM

Mybatis對映檔案Mapper.xml#和$的區別

關於Mapper.xml對映語句中什麼時候用"#"什麼時候用"$",已經有很多人做過總結,我最近在寫專案時仍然遇到了一點問題,所以在這裡結合專案文件和案例,再做一下總結,也作為個人的筆記,在這裡再總結下。 一、先看一下在mybatis api中關於"#"和"$"的描述 1、"#" 圖 1

mybatis xmlsql語句報錯: Error creating document instance. Cause: org.xml.sax.SAXPa

今天遇到了這個問題,感覺很奇怪,沒有什麼問題,但是還是會報錯。 在網上找了半天,用第二種方法解決了這個問題。第一種方法沒有嘗試。以此來記錄下。 感覺這個問題出現概率很大。要記著呢。 1、使用轉移字元替代 &lt; < &gt; &

mybatis MyBatis Mapper.xml檔案 $和#的區別

1.  MyBatis Mapper.xml檔案中 $和#的區別   網上有很多,總之,簡略的寫一下,作為備忘。例子中假設引數名為 paramName,型別為 VARCHAR 。 1.優先使用#{paramName,jdbcType=VARCHAR} 寫法,

mybatismapper.xml like用法

MySQL和oracle 資料庫中是一樣的寫法 : <select id="XXX"> SELECT * FROM user WHERE name like CONCAT('%',#{name},'%') </select>  

Mybatis之在mapper.xml提前判斷好欄位是Not Null或非空字串

①二者在一起寫,<if test="channelId != null and channelId != '' ">欄位名=#{xxx,jdbcType=VARCHAR}</if>,這種是最常用的。 ②這個取決於資料庫中,該欄位的約束。否則會報錯。

mybatis mapper.xml檔案$和#的使用區別

#{}表示一個佔位符即?,可以有效防止sql注入。在使用時不需要關心引數值的型別,mybatis會自動進行java型別和jdbc型別的轉換。 #{}可以接收簡單型別值或pojo屬性值,如果傳入簡單型別值,#{}括號中可以是任意名稱。 <!-- 根據名稱