MyBatis[二]动态SQL
动态SQL指的是:在程序运行时,根据不同的情况,拼接最终执行的sql语句
<if>
<if test="条件">
SQL片段(当条件为true就拼接SQL片段)
</if>
<where>
- 相当于where关键字,自动补全where这个关键字
- 去掉多余的and和or关键字.因为当if条件不满足时可能会产生多余的and或者or关键字,使语法错误.
<select id="selectByConditionIfAndWhere" resultType="User">
select * from user
<where>
<if test="username!=null and username!=''">
username =#{username}
</if>
<if test="sex!=null and sex!=''">
and sex=#{sex};
</if>
</where>
</select>
</mapper>
<set>
- 用在update语句中,相当于set关键字
- 去掉SQL代码片段中后面多余的逗号
<update id="updatewithSet">
update user
<set>
<if test="username!= null and username!=''">
username=#{username},
</if>
<if test="birthday !=null and birthday!=''">
birthday=#{birthday},
</if>
<if test="sex!=null and sex!=''">
sex=#{sex},
</if>
<if test="address!=null and address!=''">
address=#{address}
</if>
</set>
where id=#{id};
</update>
</mapper>
< foreach>
遍历list或其他集合,让每一条参数执行sql语句.
<delete id="deleteForeachID">
delete from user where id in
<foreach collection="ids" item="id" open="(" separator="," close=");">
#{id}
</foreach>
</delete>
</mapper>
/**
* 动态sql <foreach></foreach>
* @param ids 要删除的id集合
*/
void deleteForeachID(@Param("ids") int[] ids);
<sql>和<include>
- sql标签:定义一段SQL语句,起个名字可以重用。
- include标签:引入上面定义的SQL代码段。
<sql id="commonInsert">
insert into user(username, birthday, sex, address) VALUES
</sql>
<insert id="addAllUser" useGeneratedKeys="true" keyProperty="id">
<include refid="commonInsert">
</include>
<foreach collection="list" item="user" close=";" separator="," >
(#{user.username},#{user.birthday},#{user.sex},#{user.address})
</foreach>
</insert>
遇到问题
1. 数据库id字段设置为自增,但是删除数据再添加时id字段不连续
原因: 自增使用过的值不会再被使用
解决:数据库执行:
SET @i=0;
UPDATE user SET id=(@i:=@i+1);
ALTER TABLE user AUTO_INCREMENT=0
2. xml<sql>报错
原因:使用了sql语言检测功能,可以无视报错