1 CRUD标签
1.1 insert标签
作用:插入数据
示例:
<insert id="insert" parameterType="User">
insert into users(username,password)
values(#{username},#{password)
</insert>
1.2 update标签
作用:更新数据
示例:
<update id="update" parameterType="User">
update users
set password=${password}
where username=#{username}
</update>
1.3 select标签
作用:获取数据
示例:
<select id="getUserById" parameterType="String" resultType="User">
select *
from users
where username=#{username}
</select>
注:多个不同类型的参数最好使用parameterType="map"
1.4 delete标签
作用:删除指定数据。
示例:
<delete id="delete">
delete from users
where username = #{username}
</delete>
2 动态SQL标签
2.1 if标签
作用:用于判断传入的参数
示例:
<select id="getUserExtList" resultType="UserExt">
select T1.username,T1.password
from users T1
where 1=1
<if test="username!=null and username!=''">
and T1.username like concat('%',#{username},'%')
</if>
</select>
2.2 where标签
作用:where 标签知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将它们去除。
示例:
<select id="getUserList" resultType="com.entity.User">
select username,password
from users
<where>
<if test="username != null and username != ''">
username = #{username}
</if>
<if test="password != null and password != ''">
password = #{password}
</if>
</where>
</select>
2.3 foreach标签
作用:循环List参数,得到List中的每一项
示例:
<select id="getUserExtList" resultType="UserExt">
select T1.username,T1.password
from users T1
where 1=1
<foreach collection="keyList" item="item" open=" and (" close=")" index="index" separator=" or ">
T1.username like concat('%',#{item},'%')
</foreach>
</select>
注:更详细的foreach标签使用请查看下面这条博客
2.4 choose/when/otherwise
作用:类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
示例:
<select id="getUserList" resultType="com.entity.User">
select username,password
from users
where 1=1
<choose>
<when test="username != null and username != ''">
and username = #{username}
</when>
<otherwise>
and (t1.username = '' or t1.username is null)
</otherwise>
</choose>
</select>
2.5 sql/include
作用:重复引用sql片段。
示例:
具体使用步骤请查看以下博客。
MyBatis sql(sql片段)标签使用(定义SQL、引用SQL)https://blog.csdn.net/qq_38974638/article/details/119961002