Bootstrap

【SQL语句】动态SQL标签

概览

标签作用
<if></if>条件判断,条件成立则显示
<where></where>取代SQL语句中的where,可以配合if标签使用,当需要省略andor的时候,自动省略
<foreach></foreach>遍历传入的集合,自动添加相应格式的语句

细节

if 标签

  • test属性
    • 用来作为if的判断语句,比如:
    <select>
    	select * from form
    	<if test="name != null and name != ''">
    		where name = #{name}
    	</if>
    </select>
    

where 标签

	select * from form
	<where>
		<if test="name != null and name != ''">
			name = #{name}
		</if>
		<if test="password != null and password != ''">
			and password = #{password}
		</if>
	</where>
  • 当第一条if语句不成立但第二条if语句成立时,第二条语句的and将会被省略

foreach 标签

  • collection 集合名称
  • item 集合遍历出来的元素/项
  • separator 每一次遍历使用的分隔符 (可选)
  • open 遍历开始前拼接的片段 (可选)
  • close 遍历结束后拼接的片段 (可选)
    <insert>
        insert into form(username,name,password) values
        <foreach collection="userList" item="user" separator=",">
            (#{user.username},#{user.name},#{user.password})
        </foreach>
    </insert>
  • 最后出来的结果就是
    insert into form(username,name,password) values (username1,name1,password1), (username2,name2,password2)……
;