MyBatis是一个非常流行的ORM框架,它的特点是将SQL语句从Java代码中分离出来,从而使代码更具可读性、可维护性和可扩展性。在MyBatis中,我们可以使用动态SQL来动态生成SQL语句,以满足不同的需求。
动态SQL是MyBatis中非常强大的特性之一,它使得我们可以根据不同的条件来生成不同的SQL语句。MyBatis中的动态SQL有以下几种类型:
-
If语句:通过判断某个条件是否成立,来决定是否包含该语句片段。
-
Where语句:用于组合查询条件,只有当第一个条件成立时才会包含该语句片段。
<select id="seach" parameterType="user" resultType="user">
select * from t_user <!-- 模糊查询 -->
<where>
<if test="username!=null and username!=''">
and username like concat('%',#{username},'%')
</if>
<if test="address!=null and address!=''">
and address like concat('%',#{address},'%')
</if>
<if test="phone!=null and phone!=''">
and phone like concat('%',#{phone},'%')
</if>
</where>
</select>
-
Set语句:用于更新数据时设置值,只有当更新字段值不为null时才会包含该语句片段。
<update id="updateUser" parameterType="user">
update t_user<!-- 更新 -->
<set>
<if test="username!=null and username!=''">
username=#{username},
</if>
<if test="password!=null and password!=''">
password=#{password},
</if>
<if test="phone!=null and phone!=''">
phone=#{phone},
</if>
<if test="address!=null and address!=''">
address=#{address},
</if>
</set>
where uid=#{uid};
</update>
-
Foreach语句:用于循环处理集合或数组中的数据,可以动态生成多条SQL语句。
<delete id="deleteById" parameterType="delV0" >
delete from t_user where uid in <!-- 根据用户uID删除用户数据 -->
<foreach item="id" collection="ids" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>