Mapper文件常用標籤

1.sql語句標籤    <sql></sql><include></include>
<sql id="someFied">
   name,password,age,sex,phone
</sql>

<select id="selectData">
   select 
   <include refid="someFied">
   from  xxx 
   where id=#{id}
</select>


2.if標籤  if判斷
<select id="selectData" resultType="Product">
   select * from product
   <if test="name!=null">
       where name like concat('%',#{name},'%')
   </if>
</select>


3.<when> <otherwise>標籤
Mybatis裏面沒有else標籤,但是可以使用when otherwise標籤來達到這樣的效果
<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>

4.where標籤  where標籤裏面成立就執行,如果不成立就可以忽略wherer標籤
<select id="selectData" 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>

5.set標籤  與where標籤類似,成立時執行,不成立時可以忽略
         update的sql語句中會碰到多個字段,可以使用set標籤
<update id="updataData" parameterType="Product">
   update prduct
   <set>
       <if test="name!=null">name=#{name},</if>
       <if test="price!=null">price=#{price}</if>
   </set>
   where id=#{id}
</update>

6.foreach標籤,通常用於in這樣的語法裏
接收一個List集合時使用foreach標籤循環遍歷
<select if ="selectData" resultType="Product">
   select * from produce
   where id in
      <foreach item="item" index="index" collection="list">
           open="(" separator="," close=")">
           #{item}
       </foreach>
</select>

7.bind標籤,就像是再做一次字符串拼接,網上也有說綁定,差不多意思
<select id="listProduct" resultType="Product">
            
    <bind name="likename" value="'%' + name + '%'" />
            
     select * from   product_  where name like #{likename}
      
</select>


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章