Hibernate / MyBatis Interview questions
What is dynamic SQL in MyBatis?
Dynamic SQL refers to a set of XML elements MyBatis provides for conditionally building a SQL statement's structure at execution time based on which parameters are actually present or what values they hold, rather than needing to write out every possible combination of conditions as separate, hardcoded statements.
<select id="searchUsers" resultType="com.example.model.User"> SELECT * FROM users WHERE 1 = 1 <if test="name != null"> AND name LIKE CONCAT('%', #{name}, '%') </if> <if test="status != null"> AND status = #{status} </if> </select>
Without dynamic SQL, supporting an optional search filter (like the example above, where name and status might each independently be present or absent) would require either writing a separate statement for every combination of present/absent filters, or building SQL strings manually in application code — both approaches that dynamic SQL's <if>, <choose>, <where>, and related elements are specifically designed to avoid.
Because these elements are evaluated against the actual parameter object passed to the statement (using OGNL expressions in the test attribute), the resulting SQL genuinely differs per invocation based on real input, which is what makes MyBatis's approach to conditional queries feel closer to writing conditional logic directly than to maintaining a large number of near-duplicate static SQL statements.
More Related questions...