标签:遍历 name 标签 张三 SQL MyBatis where id 小记
1、select常用标签:
where标签,如果该标签下返回的内容是以AND 或OR 开头的,则它会剔除掉。
不使用where标签:
where
<if test=" id!=null and id!='' ">
id=12345
</if>
<if test=" name!=null and name!='' ">
and name="张三"
</if>
如果id为空,则if标签返回的就只有 and name="张三" 和前面where连起来:where and name="张三" 多了and,肯定报错。
而标签<where>下
<where>
<if test=" id!=null and id!='' ">
id=12345
</if>
<if test=" name!=null and name!='' ">
and name="张三"
</if>
</where>
如果id为空,则if标签返回的是 and name="张三" 由where 标签删除and加上where得到:where name="张三"
2、update常用标签
set标签和if标签
如果某项为null不进行更新,保持数据库原值。
update employee
<set>
<if test=" gender!=null and gender!='' ">
gender=#{gender},
</if>
<if test=" name!=null and name!='' ">
name=#{name}
</if>
</set>
where id = #{id};
另,如果name未null ,没有set标签,就多了 个逗号,因此set 的功能:如果该标签下返回的内容是以逗号结尾的,则它会剔除掉。
3、delete常用标签
foreach标签--批量删除
collection 指定要遍历的集合,list类型的参数会特殊处理封装在map中,key就叫list
item 将当前遍历出的元素赋值给指定的变量
separator 每个元素之间的分隔符
open 在遍历出所有的结果之后拼接一个开始的字符串
close 遍历出所有的结果后拼接一个结束的字符
index 索引 遍历list 的时候是索引,遍历map的时候是map的key,item即为当前项的值。
(原文:https://blog.csdn.net/qq_33574890/article/details/78828785 )
举例:
delete from employee where id in
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
传入参数 int[] ids = {1,2,3,4,5}
4、insert常用标签
<!-- 对应的插入字段的名字 -->
<sql id="key">
<trim suffixOverrides=",">
<if test=" gender!=null and gender!='' ">
gender,
</if>
<if test=" name!=null and name!='' ">
name
</if>
</trim>
</sql>
<!-- 对应的插入字段的值 -->
<sql id="values">
<trim suffixOverrides=",">
<if test=" gender!=null and gender!='' ">
#{gender},
</if>
<if test=" name!=null and name!='' ">
#{name}
</if>
</trim>
</sql>
insert into smbms_user(<include refid="key"/>) values(<include refid="values"/>)
注意:
<trim prefix="WHERE" prefixOverrides="AND|OR"> 效果等同于<where>
<trim prefix="SET" suffixOverrides=","> 效果等同于<set>
5、树形查找
比如一个作者对象有多篇文章对象
现有Author类,Article类
一对多情况:Author下有一个列表属性private List<Article> articleList;
authorMapper.xml
<resultMap id="AuthorWithArticles" type="Author">
<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
<result column="userName" property="userName" jdbcType="VARCHAR" javaType="java.lang.String"/>
//这里把user的id传过去
<collection property="articleList" column="id" select="test.mybatis.dao.articleMapper.selectArticleListByUserId" />
</resultMap>
在articlemapper.xml有对应的select方法
<select id="selectArticleListByUserId" parameterType="java.lang.String" resultType="Author" >
select * from
tb_article where AuthorId=#{Id}
</select>
更多参考:https://blog.csdn.net/weixin_42608550/article/details/81084091
标签:遍历,name,标签,张三,SQL,MyBatis,where,id,小记 来源: https://www.cnblogs.com/xz-404/p/10675872.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。