Mybatis基于XML配置的动态语句使用
根据传入参数条件,进行查询
1、标签,多场景时使用and
<select id="selectStudentByCondition" resultType="com.lxb.domain.Student">
select * from student where 1=1
<if test="name != null">
and name=#{name}
</if>
<if test="条件">
...
</if>
</select>
<!-- 注:test属性中写的时对象的属性名 -->
2、<where>
当至少有一个if子元素的条件成立,sql才会插入“where”元素,并且会自动去除多余的and和or
<select id="selectStudentByCondition" resultType="com.lxb.domain.Student">
select * from student
<where>
<if test="name != null">
name=#{name}
</if>
<if test="条件">
...AND ...
</if>
</where>
</select>
3、<foreach>遍历集合
<select id="selectStudentByCondition" resultType="com.lxb.domain.Student">
select * from student where 1=1
<where>
<if test="names != null and names.size()>0">
<foreach collection="names" open="and name in (" close=")" item="name" sperator=",">
#{name}
</foreach>
</if>
</where>
</select>
实现SQL语句:select column_name from table_name where id in(...)
collection:代表要遍历的集合元素,代码中不使用#{}
open:代表语句开始部分
close:代表结束部分
item:代表便利集合的每个元素,生成的变量名
sperator:代表分隔符
抽取重复的sql语句
定义:
<sql id="defaultSql">
select * from student
</sql>
使用:
<select ......>
<include refid="defaultSql"></include>
/<select>
本文详细介绍MyBatis中基于XML配置的动态SQL语句使用方法,包括<if>、<where>、<foreach>标签的应用,以及如何通过这些标签根据传入参数条件进行查询,实现SQL语句的动态生成。
503

被折叠的 条评论
为什么被折叠?



