MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。
MyBatis中用于实现动态SQL的元素主要有:
if
choose(when,otherwise)
trim
where
set
foreach
if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。先来看如下一个例子:
Xml代码 收藏代码
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 11 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了。
Xml代码 收藏代码
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 11 = 1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="content != null">
&nb
MyBatis中用于实现动态SQL的元素主要有:
if
choose(when,otherwise)
trim
where
set
foreach
if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。先来看如下一个例子:
Xml代码 收藏代码
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 11 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了。
mysql中。通过LAST_INSERT_ID() 获得刚插入的自动增长的id的值。
注意:selectKey中order属性的值是不同的,BEFORE先选择主键,设置keyProperty的值然后执行插入语句。
AFTER是先执行插入语句,然后执行selectKey。
Xml代码 收藏代码
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 11 = 1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="content != null">
&nb