Mybatis中动态SQL,if,where,foreach怎么用

发布时间:2021-08-09 10:38:53 作者:小新
来源:亿速云 阅读:157

这篇文章主要为大家展示了“Mybatis中动态SQL,if,where,foreach怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Mybatis中动态SQL,if,where,foreach怎么用”这篇文章吧。

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

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

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

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

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

原SQL语句:

<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)为空的话我们怎么进行灵活的处理是程序不报异常。做法利用if和where判断进行SQL拼接。

<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片段的定义

<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片段的使用

<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)

<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: 遍历的两个对象中需要拼接的串

<if test="ids != null"> 
 <foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">
  id= #{user_id}
 </foreach>
</if>

以上是“Mybatis中动态SQL,if,where,foreach怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. MyBatis动态sql
  2. 怎么在MyBatis中配置动态SQL

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis sql

上一篇:IntelliJ IDEA插件怎么用

下一篇:如何使用Material Design控件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》