gpt4 book ai didi

MyBatis 动态拼接Sql字符串的问题

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 27 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章MyBatis 动态拼接Sql字符串的问题由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空格或在列表的最后省略逗号。动态 SQL 可以彻底处理这种痛苦.

动态SQL 。

MyBatis的动态SQL,解决了SQL字符串拼接的痛苦.

1.if 。

?
1
2
3
4
5
6
7
8
< select id= "findActiveBlogWithTitleLike"
parameterType= "Blog" resultType= "Blog" >
SELECT * FROM BLOG
WHERE state = 'ACTIVE'
<if test= "title != null" >
AND title like #{title}
</if>
</ select >

这条一句会提供一个可选的文本查找功能。如果没有传递title,那么所有激活的博客都会被返回。 如果传递了title,那么就会查找相近的title.

2.choose,when,otherwise 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< select id= "findActiveBlogLike"
parameterType= "BLOG" resultType= "BLOG" >
SELECT * FROM BLOG
WHERE
<choose>
< when test= "title != null" >
AND title like #{title}
</ when >
< when test= "author != null and author.name != null" >
AND title like #{author. name }
</ when >
<otherwise>
AND featured = 1
</otherwise>
</choose>
</ select >

注:如果上述条件都没有匹配,则会变成SELECT * FROM BLOG WHERE 如果仅有第二个匹配,则会变成SELECT * FROM BLOG WHERE AND title LIKE somelike 显然这样会查询失败。要解决这个问题,mybatis提供了解决方法.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< select id= "findActiveBlogLike"
parameterType= "BLOG" resultType= "BLOG" >
SELECT * FROM BLOG
WHERE
<trim prefix= "WHERE" prefixOverrides= "AND |OR " >
<choose>
< when test= "title != null" >
AND title like #{title}
</ when >
< when test= "author != null and author.name != null" >
AND title like #{author. name }
</ when >
<otherwise>
AND featured = 1
</otherwise>
</choose>
</trim>
</ select >

overrides属性采用管道文本分隔符来覆盖,这里的空白是重要的。它的结果就是移除在InnerText中overrides中指定的内容.

3.set 。

?
1
2
3
4
5
6
7
8
9
10
< update id= "updateAuthorIfNecessary"
parameterType= "Author" >
update Author
< set >
<if test= "username != null" >username=#{username},</if>
<if test= "password != null" > password =#{ password },</if>
<if test= "email != null" >email=#{email}</if>
</ set >
where id=#{id}
</ update >

同上的问题,优化后:

?
1
2
3
4
5
6
7
8
9
10
11
12
< update id= "updateAuthorIfNecessary"
parameterType= "Author" >
update Author
<trim prefix= "where" prefixOverrides= "," >
< set >
<if test= "username != null" >username=#{username},</if>
<if test= "password != null" > password =#{ password },</if>
<if test= "email != null" >email=#{email}</if>
</ set >
where id=#{id}
</trim>
</ update >

以上所述是小编给大家介绍的MyBatis 动态拼接Sql字符串的问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我网站的支持! 。

最后此篇关于MyBatis 动态拼接Sql字符串的问题的文章就讲到这里了,如果你想了解更多关于MyBatis 动态拼接Sql字符串的问题的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com