MyBatis常用动态SQL语句
作者:不染心
时间:2022/5/25
profession类
的属性如下:
public class Profession {
private int id;
private String pro_name;
private String pro_id;
private String nourish_id;
}
一、查询
查询操作中<if test="id!=-1 and id!=0">
会根据属性id
值判断是否执行将id作为查询条件之一,该查询SQL语句可以作为搜索功能接口,如果搜索功能输入的条件之一为空就不将其作为查询条件。
<!-- 查询操作 -->
<select id="selectProfessionByConditions" resultType="Profession" parameterType="Profession">
select * from `profession`
<where>
<if test="id!=-1 and id!=0">
AND id = #{id}
</if>
<if test="pro_name!=null and pro_name!=''">
AND pro_name = #{pro_name}
</if>
<if test="pro_id!=null and pro_id!=''">
AND pro_id = #{pro_id}
</if>
<if test="nourish_id!=null and nourish_id!=''">
AND nourish_id = #{nourish_id}
</if>
</where>
</select>
<!--联表查询-->
<select id="selectProNouByConditions" resultType="ProfessionNourish">
select a.id, a.pro_name, a.pro_id, a.nourish_id, b.nourish_name, b.finish_weight
from `profession` a, `nourish` b where a.nourish_id = b.nourish_id
</select>
二、插入
<!-- 插入数据 -->
<insert id="addProfession" parameterType="Profession">
INSERT INTO `profession` (`pro_name`, `pro_id`, `nourish_id`)
VALUES(#{pro_name}, #{pro_id}, #{nourish_id})
</insert>
三、删除
<!-- 删除操作 -->
<delete id="delProfessionById">
delete from `profession` where id = #{id}
</delete>
四、更新
更新语句中使用if
语句判断属性值是否为空,如果不为空就更新该属性值,否则不更新。
<!-- 更新操作 -->
<update id="updateProfessionById" parameterType="Profession">
update `profession`
<set>
<if test="pro_name!=null and pro_name!=''">
pro_name = #{pro_name},
</if>
<if test="pro_id!=null and pro_id!=''">
pro_id = #{pro_id},
</if>
nourish_id = #{nourish_id},
</set>
where id = #{id}
</update>