MyBatis' dynamic SQL refers to the flexible operation of SQL statements; it is based on OGNL expressions and flexibly splices SQL statements through if, choose, when, otherwise, trim, where, set, and foreach tags , assembly, thus improving developer efficiency.
What is dynamic SQL? What is the role of dynamic SQL?
mybatis core Perform flexible operations on SQL statements, judge through expressions, and flexibly splice and assemble SQL.
With the traditional method of using JDBC, I believe that when you combine complex SQL statements, you need to splice them together. If you don't pay attention, even missing a space will lead to errors. The dynamic SQL function of Mybatis is designed to solve this problem. It can be combined into very flexible SQL statements through if, choose, when, otherwise, trim, where, set, and foreach tags, thereby improving the efficiency of developers
MyBatis uses OGNL to use dynamic SQL.
Currently, dynamic SQL supports the following tags
Example: if statement uses
according to username and sex to query the data. If username is empty, then it will be queried only based on sex; otherwise, it will be queried only based on username
First do not use dynamic SQL to write the above query statement
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User"> <!-- 这里和普通的sql 查询语句差不多,对于只有一个参数,后面的 #{id}表示占位符,里面不一定要写id, 写啥都可以,但是不要空着,如果有多个参数则必须写pojo类里面的属性 --> select * from user where username=#{username} and sex=#{sex} </select>
, We can find that if #{username} is empty, then the query result is also empty. How to solve this problem?
Use if to determine
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User"> select * from user where <if test="username != null"> username=#{username} </if> <if test="username != null"> and sex=#{sex} </if> </select>
Writing like this, we can see that if sex is equal to null, then the query statement is select * from user where username=# {username}
.
The above is the detailed content of What is mybatis dynamic sql. For more information, please follow other related articles on the PHP Chinese website!