动态SQL
一、where
向sql里面追加where,如果where里面没有内容,则不显示 ;如果where后面紧接着 and or等等关键字,它会默认去掉
<select id="selectAll" resultType="com.gx.domain.User">
select * from user
<where>
<!-- and 1=1 or 2=2 -->
</where>
</select>
二、if
判断某个条件是否成立,如果成立可以拼接sql,不成立不拼接
<select id="selectAll" resultType="com.gx.domain.User">
select * from user
<where>
<!-- and 1=1 or 2=2 -->
<if test="name!=null">
and name like "%"#{name}"%"
</if>
<if test="address!=null">
and address like "%"#{address}"%"
</if>
</where>
</select>
三、choose(when,otherwise)
相当于java里面的if, else if , else ,要根据某一个条件做单条件查询的时候要使用
<select id="selectAll" resultType="com.gx.domain.User">
select * from user
<where>
<choose>
<when test="name!=null">
and name like "%"#{name}"%"
</when>
<when test="address!=null">
and address like "%"#{address}"%"
</when>
<otherwise></otherwise>
</choose>
</where>
</select>
四、set
修改的时候为sql加一个set的字符串
当修改一个实体时,如果只传了一个id和name,只修改name,其他不修改
<update id="updateBySelective" parameterType="User">
<!-- update user set name=#{name},address=#{address},birthday=#{birthday} where id=#{id} -->
update user
<set>
<if test="name!=null">
name=#{name}
</if>
<if test="address!=null">
address=#{address}
</if>
<if test="birthday!=null">
birthday=#{birthday}
</if>
</set>
<where>
id=#{id}
</where>
</update>
五、foreach:循环遍历
<select id="selectAllInIds" resultType="User" parameterType="Integer[]">
select * from user
<where>
<!-- id in (
<foreach collection="array" item="id" separator=",">
#{id}
</foreach>
) -->
<!--
collection:代表数据或集合
item:代表循环的值
index:循环变量 索引
open:循环时字符串的最开始的值
separator:循环的分隔符
close:循环结束之后追加的字符串
-->
<foreach collection="array" item="id" open="id in(" separator="," close=")">
#{id}
</foreach>
</where>
</select>
方法
/** * 查询id在Integer[]里面的数据 */ public List<User> selectAllInIds(Integer[] ids);
测试
@Test
public void selectAllInIds() {
Integer[] ids= {1,2,3,4,5};
List<User> list = userMapper.selectAllInIds(ids);
for (User user2 : list) {
System.out.println(user2);
}
MyBatisUtils.closeSession(session);
}

浙公网安备 33010602011771号