mybatis动态sql查询语句 以单表查询为列子
- if —条件判断
2.where : 自动增加where ,去除第一个and
3.choose when if()else if --else{}
4.set --修改 自动增加set 去除最后一个,
5.trim —可以增加,删除 前缀/后缀
6.foreach—in
7.bind —模糊查询
8.sql --抽取公共的sql片段
9.include --sql包含
OGNL表达式—一种介于java和javascript直间的语言,简单来讲就是整合语言。
<select id="selectMoer1" resultType="flower">
select * from flower where 1=1
<!-- OGNL表达式 -->
<if test="param1!=null and param1!=''">
and name =#{param1}
</if>
<if test="param2!=null and param2!=''">
and production=#{param2}
</if>
</select>
<select id="selectMoer2" resultType="flower">
select * from flower
<where>
<if test="param1!=null and param1!=''">
and name =#{param1}
</if>
<if test="param2!=null and param2!=''">
and production=#{param2}
</if>
</where>
</select>
//单表查询
<select id="selectMoer3" resultType="flower">
select * from flower
<where>
<choose>
<when test="param1!=null and param1!=''">
and name=#{param1}
</when>
<when test="param2!=null and param2!=''">
and production=#{param2}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
</select>
<update id="updateFlow" >
update flower
<set>
<if test="param1!=null and param1!=''">
name =#{param1} ,
</if>
<if test="param2!=null and param2!=''">
production=#{param2},
</if>
id =#{param3},
</set>
where id =#{param3}
</update>
<update id="updateFlow2" >
update flower
<trim prefix="set" suffixOverrides=",">
<if test="param1!=null and param1!=''">
name =#{param1} ,
</if>
<if test="param2!=null and param2!=''">
production=#{param2},
</if>
id =#{param3},
</trim>
where id =#{param3}
</update>
<select id="selectMore4" resultType="flower">
SELECT id,name, price FROM flower WHERE id IN
<foreach collection="list" open="(" separator="," close=")" item="it">
#{it}
</foreach>
</select>
<select id="selectMore5" resultType="flower">
select <include refid="sq1"></include> from flower where 1=1
<!-- OGNL表达式 -->
<if test="param1!=null and param1!=''">
<bind name="pa" value="'%'+param1+'%'"/>
and name like #{pa}
</if>
<if test="param2!=null and param2!=''">
and production = #{param2}
</if>
</select>
<sql id="sq1">
id,name
</sql>
<select id="selectMore6" resultType="flower">
select * from flower where ${param1}=#{param2}
</select>