1.什么是动态SQL 传统的使用JDBC的方法,相信大家在组合复杂的的sql语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。mybatis的动态SQL功能正是为了解决这种问题, 其通过 if
1.什么是动态SQL
传统的使用JDBC的方法,相信大家在组合复杂的的sql语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率。
SQL语句不固定, 会根据前台用户的操作而进行变化的SQL语句, 可以被称之为动态SQL. 在MyBatis中, 提供了一组标签, 用于方便的实现动态SQL, 不需要通过java代码拼接字符串了.
###2.动态sql中的标签
1. <if>
用于条件判断, test属性表示判断结果, 要求是一个boolean.
2.<where>
用于维护where子句, 通常配合一起使用. 如下功能:
a)当没有条件时, 不会创建WHERE关键字;
b)当有条件时, 会自动生成WHERE关键字;
c)会自动去掉第一个条件的and/or关键字.
3.<choose><when><otherwise>
功能类似于switch…case…default, 表示多分支判断, 只能成立一个条件
<mapper namespace="com.bjsxt.mapper.UserMapper">
<select id="selByCondition" resultType="user">
select * from tb_user
<where>
<if test="id != null">
and id=#{id}
</if>
<if test="username != null and username != ''">
and username=#{username}
</if>
<if test="age != null">
and age <> #{age}
</if>
<choose>
<when test="birthday != null and birthday != ''">
and birthday = #{birthday}
</when>
<otherwise>
and birthday is null
</otherwise>
</choose>
</where>
</select>
</mapper>
--结束END--
本文标题: Mybatis4 之Mybatis动态sql的实现代码
本文链接: https://www.lsjlt.com/news/50151.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-16
2024-03-15
2024-03-15
2024-03-15
2024-03-15
2024-03-15
2024-03-15
2024-03-15
2024-03-15
2024-03-14
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0