-
sql标签与include标签的配合使用
a. sql标签定义数据库字段<sql id="my_user"> USER_ID,USERNAME,PASSWORD </sql>
b.include 引用sql标签中的id
<select id="selectByUsername" parameterType="java.lang.String" resultType="com.bviz.model.User"> select <include refid="my_user" /> from T_USER where USERNAME = #{USERNAME} </select>
-
if先对某个内容进行判定:
<select id="selectByUsername" parameterType="com.model.User" resultType="com.model.User"> select from T_USER where <if test="user.username != null and user.username != ''" > id = #{user.id} </if> <if test="user.username != null and user.username != ''" > and username like "%"#{user.username}"%" </if> </select>
在更新语句中使用
<update id="updateByPrimaryKeySelective" parameterType="com.bviz.model.Authority"> update T_AUTHORITY <set> <if test="authName != null"> AUTH_NAME = #{authName,jdbcType=VARCHAR}, </if> <if test="authCode != null"> AUTH_CODE = #{authCode,jdbcType=VARCHAR}, </if> <if test="authDesc != null"> AUTH_DESC = #{authDesc,jdbcType=VARCHAR}, </if> <if test="pId != null"> P_ID = #{pId,jdbcType=VARCHAR}, </if> </set> where ID = #{id,jdbcType=VARCHAR}
-
foreach:foreach 共有List array Map三种使用场景,主要用在构建in条件中,可以在SQL语句中进行迭代一个集合
a.List类型插入:<insert id="insertDevice" parameterType="java.util.List"> INSERT INTO t_device(order_no, mac_id, client_code, status) <foreach collection="list" item="item" index="index" separator="union all"> select #{item.orderNo,jdbcType=VARCHAR}, #{item.macId, jdbcType=VARCHAR} from dual </foreach> </insert>
dual是Oracle中的一个伪表,利用这个伪表可以设置或查看序列,或者是调用一些内置的函数,可以很方便的时候。
比如:
SELECT sysdate FROM daul:求得系统当前时间b.List类型查询
<select id="selectDevice" parameterType="java.util.List" resultType="Device"> SELECT * FROM t_device WHERE id in <foreach collection="list" item="item" index="index" open="(" separator="," close=")"> #{item} </foreach> </select>
4.set标签: set标记是mybatis提供的一个智能标记,常用语更新语句中,
<update id="updateDevice" parameterType="Device">
UPDATE t_device
<set>
<if test = "macId != null and macId != ''">
MAC_ID = #{macId},
</if>
<if test = "clientCode != null and clientCode != ''">
CLIENT_CODE = #{clientCode},
</if>
</set>
where
ORDER_NO = #{orderNo}
</update>
注意最后一个<if>中也有一个逗号,系统最终会自动删除
5.trim标签:
有四个属性:
prefix:给SQL语句拼接的前缀
suffix:给SQL语句拼接的后缀
prifixOverrides:去除sql语句前面的关键字
suffixOverrides:去除sql语句后面的关键字
<insert id="insertDevice" parameterType="Device">
INSERT INTO T_DEVCIE
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="orderNo != NULL"> ORDER_NO,</if>
<if test="macId != NULL"> MAC_ID,</if>
<if test="clientCode != NULL"> CLIENT_CODE,</if>
<if test="status != NULL"> STATUS,</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="orderNo != NULL"> #{orderNo,jdbcType=VARCHAR},</if>
<if test="macId != NULL"> #{macId,jdbcType=VARCHAR},</if>
<if test="clientCode != NULL"> #{clientCode,jdbcType=VARCHAR},</if>
<if test="status != NULL"> #{status,jdbcType=VARCHAR},</if>
</trim>
</insert>