Mybatis核心知识点

1. 经常使用标签

1. <where>标签java

至关于sql语句中的where关键字sql

<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="条件字符串",判断是否知足条件,知足则执行,不知足则跳过。code

3. <set>标签字符串

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

<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> 标签组it

条件判断的标签组,至关于Java的switch-case,匹配<when>中的条件,一旦匹配到立刻结束;若匹配不到,执行<other>中的语句。io

<!-- 查询短信发送记录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>标签test

<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>
相关文章
相关标签/搜索