1. 程式人生 > >Mybatis中動態SQL

Mybatis中動態SQL

if

<select id="selByAccinAccout" resultType="Log">
		select * from log where 1=1	
			<if test="accin!=null and accin!=''">
				and accin=#{accin}
			</if>
			<if test="accout!=null and accout!=''">
				and accout=#{accout}
			</if>			
	</select>

where(去掉第一個and)

<select id="selByAccinAccout" resultType="Log">
		select * from log
		<where>
			<if test="accin!=null and accin!=''">
				and accin=#{accin}
			</if>
			<if test="accout!=null and accout!=''">
				and accout=#{accout}
			</if>		
		</where>
	</select>

choose

<select id="selByAccinAccout" resultType="Log">
		select * from log
		<where>
			<choose>
				<when test="accin!=null and accin!=''">
					and accin=#{accin}
				</when>
				<when test="accout!=null and accout!=''">
					and accout=#{accout}
				</when>				
			</choose>		
		</where>		
	</select>

set(去掉最後一個逗號)

<update id="upd" parameterType="Log">
		update log
		<set>
			id=#{id},
			<if test="accin!=null and accin!=''">
				accin=#{accin},
			</if>
			<if test="accout!=null and accout!=''">
				accout=#{accout},
			</if>			
		</set>
		where id=#{id}
	</update>