六、Mybatis之常用标签

所有的标签


(一)<where>标签
    <where>标签一般与<if>标签一起使用。用了where关键字就不用再Sql语句后面加where1=1来拼接,<where>标签会
帮我们补上where关键字,假如<where>标签下的<if>条件都不满足,<where>标签与不会为我们添加where关键字。当<where>
标签下的<if>条件满足多个时,拼接语句添加" and command=#{command}",因为用了<where>标签,它会把where关键字
之后的第一个and关键字出掉.即会变成一条符合规范的sql语句. 
<select id="find" resultMap="resultMap"> 
select * from Message 
<where> 
<if test="command!=null"> and comand =#{command} </if> 
<if test="description!=null"> and description =#{descrtiption} </if> 
</where> 
</select>

(二)<set>标签
    <set>标签与<where>标签同级,<set>标签其实就是代替<where>标签的where关键字。也经常与<if>标签配合使用,
会自动添加逗号,功能与<wherer>标签相似. 
<update id="updateset" parameterType="com.imooc.Message"> 
update message 
<set> 
<if test="command!=null"> command=#{command} </if> 
<if test="description!=null"> description=#{description} </if> </set> 
</update>

(二)<choose>标签
    <choose>标签有<when test="">和<otherwise>子标签, 相当于
    if(){}
    else if(){}
    else{} 
语句。
<select > 
select * from message 
<choose> 
<when test=""></when> 
<when test=""></when> 
<otherwise></otherwise> 
</choose> 
</select>

(三)<sql>标签
    <sql>标签,此标签与<select>、<update>这些标签同一个级别。<sql>标签与java中的常量定义一个意思。
即可以把经常用到的一些sql语句把它放在<sql>标签下,在<sql>标签下添加id属性。在要用到<sql>标签的位置添加
<include refid="sql标签的id值">标签即可。 
<select id="find" resultMap="resultMap"> 
select <include refid="sql1"> from message </select> 
<sql id="sql1">command,description,content</sql> 
一般<sql>标签存的是列名,因为在要插入数据或者查询数据时直接引用sql常量会比较方便.

(四)<trim>标签
    <trim>标签在<select>/<update>等内使用。
    prefix:往前面加内容; 
    prefixOverrides:去除前面不需要的内容; 
    suffixOverrides:去掉后面不需要的内容;
    <trim prefix="where" suffix="test" prefixOverrides="andor" suffixOverrides=","> 
    </trim> 
    //提示:prefix="where" prefixOverrides="andor"等价于<where>;
    //prefix="set" suffixOverrides=","等价于<set>。

猜你喜欢

转载自blog.csdn.net/panchang199266/article/details/80264734