mybatis标签——动态sql语句

在mapper映射文件中写入

1. if标签

条件写在test

select * from user where 1=1 
  <if test="user.age!=-1 ">
  and user.age=#{userAge}<--and 用于拼接sql语句 -->
   </if>

2. where 标签——解决 where 1=1拼接

select * from user 
<where>
  <if test="userAge!=-1 ">
  and userAge=#{userAge}<--and 用于拼接sql语句 -->
   </if>
     <if test="userSex!=null ">
  and userSex=#{userSex}   <--and 用于拼接sql语句 -->
   </if>
   </where>

3.foreach标签——子查询使用

select * from user where id in (10,20,30 )

select *from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (”close=")" item="uid" separator=",">
#{uid}
</ foreach>

其中item决定下面的#{ }里的名字,ids是getIds得到的容器,从中获取item

4. sql标签——抽取重复的代码片段

用于抽取公共代码片段

4.1 抽取片段

<sql id="findUserTab">
select * from user
</sql>

4.2 引入代码片段

<include ref="findUserTab"></include >
发布了25 篇原创文章 · 获赞 25 · 访问量 1045

猜你喜欢

转载自blog.csdn.net/Android_Cob/article/details/105187859