sql标签
select * from tableName;
select 字段名 from tableName;
上面两个语句相比,语句二性能更高一点。执行语句一时,系统会将 * 先解析成表中的每一个字段,因此性能稍低一点。
在mybatis中提供 sql标签,将查询的字段放在sql标签中,通过include标签进行引用,可使性能更高。使用方法如下:
<sql id='sqlBiaoQian'>
student_id,student_name,student_sex,student_age
</sql>
<select id="sql" resultType="student">
select <include refid="sqlBiaoQian"></incleude> from student
</select>
if标签、where标签和trim标签
if标签
选择满足条件的数据
<sql id='sqlBiaoQian'>
student_id,student_name,student_sex,student_age
</sql>
<select id="sql" resultType="student">
select <include refid="sqlBiaoQian"/> from student where
<if test="studentId != null and studentId != ' ' ">
student_id = #{studentId}
</if>
<if test="studentName != null and studentName != ' ' ">
and student_name = #{studentName}
</if>
</select>
where标签
在上面的sql语句中存在的问题有:
- 当没有满足条件的 if 时,sql语句变为下面的语句,该语句是错误的SQL语句。
select <include refid="sqlBiaoQian"/> from student where ;
- 当第一个 if 为空,sql 语句变为下面的语句,有多余的and出现,该语句也会执行错误。
select <include refid="sqlBiaoQian"/> from student
where and student_name = studentName ;
where标签就很好的解决了上述两个问题:
- 当where语句后无判断条件时,where标签便不会生成where查询条件。
- 当where语句中前面多余的and时,where标签会自动帮助我们去掉第一个多余的and。
trim标签
问题来了,在条件语句前出现多余的 and 用where标签可以自动去除掉,那么条件语句后出现多余的 and 怎么处理呢?tirm 标签就能帮助我们很好的解决此问题,下面我们一起来看看 trim 标签的用法吧。
属性 | 作用 |
---|---|
prefix | 在sql语句中添加一个前缀 |
prefixOverrides | 去掉SQL语句前多余的内容;这里去掉多余的 AND 和where标签的作用相似 |
suffix | 在sql语句中添加一个后缀 |
suffixOverrides | 去掉SQL语句后多余的内容 |
foreach标签
foreach标签的作用是进行批量操作。如下SQL语句:
select * from Employee where emp_id in (101,102,103,104);
在Mybatis中的写法如下:
<sql id='sqlBiaoQian'>
student_id,student_name,student_sex,student_age
</sql>
<select id="sql" resultType="student">
select <include refid="sqlBiaoQian"/> from student
<where>
student_id in
<foreach collection="list" item="studentId" open="(" close=")" separator="," >
#{studentId}
</foreach>
</where>
</select>
foreach标签中各属性标签的含义如下:
属性 | 作用 |
---|---|
collection | 当前循环的内容,即循环的入参 |
item | 循环体中每条数据的别名 |
open | 设置当前循环的内容以什么开始,可选参数。 |
close | 设置当前循环的内容以什么结束,可选参数。常以open=“(” close=")"配合使用 |
separator | 每次循环数据之间的分隔符,例如:student_id in (#{studentId} ,#{studentId})在读取每一个studentId值后会自动添加:逗号。 |
choose、when、otherwise标签
choose、when、otherwise三个标签常组合起来使用,相当与JAVA中的 switch、case、default。使用如下:
<select id="dynamicSql2" resultMap="student">
select <include refid="sqlBiaoQian"/> from student
<where>
<choose>
<when test="name != null and name != ''">
AND name = #{name}
</when>
<when test="grade != null and grade != ''">
AND grade = #{grade}
</when>
<otherwise>
AND student_id = #{studentId}
</otherwise>
</choose>
</where>
</select>