mybatis中的动态SQL(if,trim,where,set,foreach标签)
·
mybatis中的动态SQL的使用
if标签
- mapper层中的查询方法
//现在不确定哪个参数是必填的,哪个参数是非必填的
public List<ArticleInfo> getArticleInfo(@Param("title") String title, @Param("content") String content, @Param("state") int state);
- mapper.xml中的sql方法
<select id="getArticleInfo" resultMap="BaseResultMap">
select * from articleinfo where 1=1
<if test="title!=null">
and title=#{title}
</if>
<if test="content!=null">/*这个test中的content是mapper层传进来的@Param中设置的参数的值*/
and content=#{content}
</if>
<if test="state!=0">
and state=#{state}
</if>
</select>
- 测试结果
@Test
void getArticleInfo() {
List<ArticleInfo> list = articleInfoMapper.getArticleInfo(null,null,0);
list.forEach(System.out::println);
}

if标签总结
- 这里为了避免输入的三个参数都为空,语法出错,所以使用1=1,这样没问题,但是有点不雅,下面的trim标签可以解决这个问题。
- 要注意/*这个test中的content是mapper层传进来的@Param中设置的参数的值
trim标签
- mapper层中的查询方法:
//这三个参数是非必填的
public List<ArticleInfo> getArticleInfo2(@Param("title") String title,@Param("content") String content,@Param("state") int state);
- mapper.xml中的sql方法:
<select id="getArticleInfo2" resultMap="BaseResultMap">
select * from articleinfo
<trim prefix="where" prefixOverrides="and">
<if test="title!=null">
and title=#{title}
</if>
<if test="content!=null">
and content=#{content}
</if>
<if test="state!=0">
and state=#{state}
</if>
</trim>
</select>
- 测试结果:


trim标签总结
- 当trim标签中的所有if都为false时,那么trim标签的前缀和后缀属性值都不会生效(prefix,prefixOverrides,suffix,suffixOverrides)
where标签
- mapper查询方法
//这三个参数是非必填的
public List<ArticleInfo> getArticleInfo3(@Param("title") String title,@Param("content") String content,@Param("state") int state);
- mapper.xml中的sql方法
<select id="getArticleInfo3" resultMap="BaseResultMap">
select * from articleinfo
<where>
<if test="title!=null">
and title=#{title}
</if>
<if test="content!=null">
and content=#{content}
</if>
<if test="state!=0">
and state=#{state}
</if>
</where>
</select>
- 测试结果:测试结果成功


where标签总结
- where标签很优雅,在查询语句中,只需要在if标签里全部加上and关键字即可,它会自动去掉第一个if中的and关键字,并且如果所有if都不满足的话,整个where标签都不会执行

set标签
- mapper中的查询方法

- mapper.xml中的sql方法
<update id="upArticle">
update articleinfo
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="content!=null">
content=#{content},
</if>
</set>
where id=#{id}
</update>
- 测试结果


set标签总结
- 这个是用于修改的一个标签,和where标签类似,很优雅,只需要在里面所有if标签里都加上“,”,它会自动把最后一个逗号去掉
- set标签里的所有if标签不能都为false,否则sql语法错误
foreach标签
- mapper中的查询方法

- mapper.xml中的sql方法

- 测试结果:


总结

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)