动态SQL查询
if+where: 用于查询操作,where标签可以智能判断是否添加and、or、where关键词
示例:
<select id="findByParam" resultType="com.accp.pojo.User">
select * from user
<where>
<if test="gender!=null">
gender=#{gender}
</if>
<if test="userName!=null">
and userName like CONCAT('%',#{userName},'%')
</if>
</where>
</select>
if+set: 用于更新操作,set标签可以智能判断每个if条件后是否添加","
示例:
<update id="updateUser" parameterType="com.accp.pojo.User">
update user
<set>
<if test="userName != null">
userName = #{userName},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="address != null">
address = #{address},
</if>
<if test="gender != null">
gender = #{gender}
</if>
</set>
where id = #{id}
</update>
trim:
prefix:前缀
suffix:后缀
prefixOverrides:自动判断子语句if前面的条件语句是否添加或不添加其值
suffixOverrides:自动判断子语句if后边的条件语句是否添加或不添加其值
示例:
<update id="updateUser" parameterType="com.accp.pojo.User">
update user
<trim prefix="set " suffixOverrides="," suffix=" where id = #{id}" >
<if test="userName != null">
userName = #{userName},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="address != null">
address = #{address},
</if>
<if test="gender != null">
gender = #{gender}
</if>
</trim>
</update>
foreach: 更新操作,或者用在insql语句中
collection:传进来的参数类型
List集合写成:”list”;
数组写成:”array”;
其他复杂类型写成:参数使用map 这里写map的key
item:临时变量(每一个迭代元素的别名)
open:该语句以什么开始
close:该语句以什么结束
separator:多个迭代元素以什么分隔(符)
示例:
<select id="findByIds" resultType="com.accp.pojo.User">
select * from user where id in
<foreach collection="list" item="usreIds" open="(" separator="," close=")">
#{usreIds}
</foreach>
</select>
<select id="getUserListById_array" resultType="com.accp.pojo.User">
select * from user where id in
<foreach collection="array" item="ids" open="(" separator="," close=")">
#{ids}
</foreach>
</select>
choose:一般使用在多个条件时只想查询其中一个
when
otherwise
示例:
<select id="findByParams" resultType="com.accp.pojo.User">
select * from user where 1=1
<choose>
<when test="userName!=null">
and userName like CONCAT('%',#{userName},'%')
</when>
<when test="phone!=null">
and phone = #{userName}
</when>
<otherwise>
and address like CONCAT('%',#{address},'%')
</otherwise>
</choose>
</select>
本文来自博客园,作者:后山人,转载请注明原文链接:https://www.cnblogs.com/zhuhuibiao/p/9402408.html
经营好自己的现在,等待未来向我飞奔而来。