作为条件判断,如果满足if条件,则if标签上的内容便会自动拼接导sql语句中
- <select id="xxx" resultType="xxx">
- select * from t_xxx where 1=1
- <if test="a != '' and a != null"> and a = #{a}if>
- <if test="b != '' and b != null"> and b = #{b}if>
- <if test="c != '' and c != null"> and c = #{c}if>
- select>
通过if语句对sql语句进行动态拼接以满足不同条件下的开发目标是一个降低耦合的好办法,但是因为sql语句条件下需要and 或者 or 连接条件,所以单单使用if语句并不能很好的解决问题,这个使用就可以在连接if语句之前加上一个永真语句就可以解决,也可以和后面的语句配合使用。
where是一个连接语句一般用来和if配合使用
若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的 and去掉
- <select id="xxx" resultType="xxx"> select * from t_xxx
- <where>
- <if test="a != '' and a != null"> a = #{a}if>
- <if test="b != '' and b != null"> and b = #{b}if>
- <if test="c != '' and c != null"> and c = #{c}if>
- where>
- select>
trim用于去掉或添加标签中的内容
prefix:在trim标签中的内容的前面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffix:在trim标签中的内容的后面添加某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容
使用trim也可以很好的解决if语句添加多或者少的问题
- <select id="xxx" resultType="xxx"> select * from t_xxx
- <trim prefix="where" suffixOverrides="and">
- <if test="a != '' and a != null"> a = #{a}if>
- <if test="b != '' and b != null"> and b = #{b}if>
- <if test="c != '' and c != null"> and c = #{c}if>
- trim>
- select>
相当于if...else if...else
就是和Java语法完全相同就是换了一个名称
- <select id="xxx" resultType="xxx">
- select * from t_xxx <where>
- <choose>
- <when test="a != '' and a != null"> a = #{a}when>
- <when test="b != '' and b != null"> b = #{b}when>
- <when test="c != '' and c != null"> c = #{c}when>
- choose>
- where>
- select>
循环语句用于实现批量添加或者批量删除或者批量修改
- <insert id="xxxx">
- insert into t_xxx values
- <foreach collection="xxx" item="xxx" separator=",">
- (null,#{xxx.x},#{xxx.x},#{xxx.x},#{xxx.x},null)
- foreach>
- insert>
collection:用来接受传过来的集合片段
item:用来取出集合中的一个元素
separator:用来给每一次给各个循环中间加上连接符
sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入
- <sql id="Columns"> xxx,xxx,xxx,xxx,xxxsql>
- select <include refid="Columns">include> from t_xxx
一直用 * 在未来开发中是不规范的,因为*其实在数据库内部也是发生转换变成全部属性的,所以直接写就可以直接避免转换的步骤,但是每次都写难免麻烦,这个时候就可以把片段变成sql片段就可以直接调取
以上就是关于动态sql的基本标签的认识啦
如有错误欢迎指出