Java教程

Mybatis动态SQL

本文主要是介绍Mybatis动态SQL,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.if标签

举例说明:

 <select id="selectid" resultType="dao.student">
        select id,name,email,age from students
<if test="id>0">//test是条件,为真时加入if内的语句,假则不加
    where id=#{id}
</if>
    </select>

2where标签

在使用它的时候,where标签内会有一个或多个if标签。如果有if标签的test为true,则where标签变为WHERE加到SQL语句后,并且如果WHERE后面是or等语句就删除。若没有if标签的test为true则忽略where标签。

举例:

 <select id="selectid" resultType="dao.student">
        select id,name,email,age from students
<where>
<if test="id>0">
   id=#{id}
</if>
</where>
    </select>

3.foreach标签

foreach可以循环数组(array)和List(list)集合,一般在in语句中使用

举例:

  <select id="selectid" resultType="dao.shiti.student">
        select id,name,email,age from students where id in
<foreach collection="集合类型" close="结束的字符"  open="开始的字符" separator="集合成员之间的分割符" item="集合中的成员">
    #{集合中的成员}//若集合中的成员是对象,该处改为 集合中的成员.属性
</foreach>
    </select>

这篇关于Mybatis动态SQL的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!