Mybatis核心知识点

1. 常用标签

1. <where>标签

相当于sql语句中的where关键字

<select id="getBy" resultMap="BaseResultMap" parameterType="java.util.Map" >
select CONTENT, PHONE, CREATE_DATE, CREATE_TIME, SMS_TYPE, STATUS
from sms_record
<where>
    <if test="id != null ">id=#{id}</if>
	<if test="channelType != null and  channelType != ''"> 
		<![CDATA[ and CHANNEL_TYPE = #{channelType} ]]>
	</if>
</where>	
</select>

2. <if>条件判断标签

条件判断标签,配置属性test="条件字符串",判断是否满足条件,满足则执行,不满足则跳过。

3. <set>标签

配合<if>标签在更新语句中使用,可以判断某个参数为空或者不合法时不更新到数据库。

<update id="updateByPrimaryKey" parameterType="com.tech.facade.message.entity.SmsRecord" >
    update sms_record
	<set >  
		<if test="PHONE != null" >  
			PHONE = #{PHONE,jdbcType=VARCHAR},  
		</if>  
		<if test="STATUS != null" >  
			STATUS = #{STATUS,jdbcType=INTEGER},  
		</if>  
	</set>
    where SMS_ID = #{smsId,jdbcType=BIGINT}
</update>

4. <choose><when></when><otherwise></otherwise></choose> 标签组

条件判断的标签组,相当于Java的switch-case,匹配<when>中的条件,一旦匹配到马上结束;若匹配不到,执行<other>中的语句。

<!-- 查询短信发送记录list,channelType:通道类型(亿美:YIMEI,)、 或=短信类型:smsType、 或=发送状态:status(0,成功,其它失败)使用choose -->       
<select id="getStudentListChooseEntity" parameterType="com.tech.facade.message.entity.SmsRecord" resultMap="BaseResultMap">       
    SELECT * from sms_record sr        
    <where>       
        <choose>       
            <when test="channelType!=null and channelType!='' ">       
                    sr.channelType = #{channelType}        
            </when>       
            <when test="smsType!= null and smsType!= '' ">       
                    AND sr.SMS_TYPE = #{smsType}        
            </when>       
            <when test="status!=null" and status!='' ">       
                AND sr.STATUS = #{status}        
            </when>            
            <otherwise>       
                        
            </otherwise>       
        </choose>       
    </where>       
</select>  

5. <foreach>标签

<foreach>标签实现sql条件的循坏,可完成类似批量的sql。

主要属性:

  • item:表示集合每一个元素进行迭代时的别名
  • index:表示在迭代过程中,每次迭代到的位置
  • open:表示该语句以什么开始
  • separator:表示每次迭代之间以什么符号作为分隔
  • close:表示该语句以什么结束
  • collection:需要迭代的变量
<!-- 找出PID等于传入ID列表的商品(父分类下的子商品)-->
<select id="selectProductIn" resultType="com.test.Product">
  SELECT *
  FROM PRODUCT P
  WHERE PID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
<!--添加订单商品表。因为一个订单可能有多个商品,因此这里进行批量添加。-->
<insert id="addOrdergood"  parameterType="java.util.List"><!-- parameterType="java.util.List"可以省略,Mybatis会自动判断参数类型。 -->
	insert into ordergood(oid,gid,count,price,allprice,profit) values
	<foreach collection="list" item="og" separator=","><!-- separator="," 不可以省略;item="og"是集合中每一个元素进行迭代时的别名,可以随便取。 -->
		(#{og.orders.oid},#{og.goods.gid},#{og.price},#{og.count},#{og.allprice},#{og.profit})
	</foreach>
</insert>

猜你喜欢

转载自my.oschina.net/u/2484728/blog/1154020