Mybatis中动态SQL,if,where,foreach的使用教程详解

2025-05-27 0 15

MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。

MyBatis中用于实现动态SQL的元素主要有:

mybatis核心 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。

1、statement中直接定义使用动态SQL

在statement中利用ifwhere 条件组合达到我们的需求,通过一个例子来说明:

原SQL语句:

?

1

2

3

4
<select id="findUserByUserQuveryVo" parameterType ="UserQueryVo" resultType="UserCustom">

select * from user

where username = #{userCustom.username} and sex = #{userCustom.sex}

</select>

现在需求是,如果返回值UserCustom为空或者UserCustom中的属性值为空的话(在这里就是userCustom.username或者userCustom.sex)为空的话我们怎么进行灵活的处理是程序不报异常。做法利用ifwhere判断进行SQL拼接。

?

1

2

3

4

5

6

7

8

9

10

11

12

13
<select id="findUserByUserQuveryVo" parameterType ="UserQueryVo" resultType="UserCustom">

select * from user

<where>

<if test="userCustom != null">

<if test="userCustom.username != null and userCustom.username != ''"><!-- 注意and不能大写 -->

and username = #{userCustom.username}

</if>

<if test="userCustom.sex != null and userCustom.sex != ''">

and sex = #{userCustom.sex}

</if>

</if>

</where>

</select>

有时候我们经常使用where 1=1这条语句来处理第一条拼接语句,我们可以使用< where > < where />来同样实现这一功能。

2、使用sql片段来处理statement

和我们写程序一样,有时候会出现一些重复的代码,我们可以用SQL片段来处理。在sql片段中需要注意的是它的位置,我们也可以引用其它mapper文件里面的片段,此时需要我们定义它的位置。

(1)、sql片段的定义

?

1

2

3

4

5

6

7

8
<sql id="query_user_where">

<if test="sex != null and sex != ''">

and sex = #{sex}

</if>

<if test="id != null">

and id = #{id}

</if>

</sql>

(2)、sql片段的使用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
<select id="findUserList" parameterType="User" resultType="User">

select * from user

<where>

<!-- 引用Sql片段 -->

<include refid="query_user_where"></include>

<!-- 在这里还要引用其它的sql片段 -->

<!--

where 可以自动去掉条件中的第一个and

-->

<!-- <if test="sex != null and sex != ''">

and sex = #{sex}

</if>

<if test="id != null">

and id = #{id}

</if> -->

</where>

</select>

3、使用foreach进行sql语句拼接

在向sql传递数组或List,mybatis使用foreach解析,我们可以使用foreach中元素进行sql语句的拼接,请求数据。

通过一个例子来看:

需求:SELECT * FROM USER WHERE id=1 OR id=10 OR id=16

或者:SELECT * FROM USER WHERE id IN(1,10,16)

?

1

2

3

4

5

6
<if test="ids != null">

<foreach collection="ids" item="user_id" open="AND (" close=")" separator="or" >

每次遍历需要拼接的串

id= #{user_id}

</foreach>

</if>

其中,collection:指定输入对象中集合属性,item: 每个遍历生成对象,open:开始遍历时拼接串,close: 结束遍历是拼接的串,separator: 遍历的两个对象中需要拼接的串

?

1

2

3

4

5
<if test="ids != null">

<foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">

id= #{user_id}

</foreach>

</if>

总结

以上所述是小编给大家介绍的Mybatis中动态SQLif,where,foreach的使用教程,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:https://www.2cto.com/database/201711/696473.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Mybatis中动态SQL,if,where,foreach的使用教程详解 https://www.kuaiidc.com/77449.html

相关文章

发表评论
暂无评论