Hibernate / MyBatis Interview questions
Explain the internal working of the foreach element for batch operations?
The <foreach> element iterates over a Java collection or array parameter, repeating a specified SQL fragment once per item and joining the repetitions with a configurable separator — most commonly used to build an IN (...) clause from a list of values, or to construct a multi-row insert.
<select id="selectUsersByIds" resultType="User"> SELECT * FROM users WHERE id IN <foreach item="id" collection="list" open="(" separator="," close=")"> #{id} </foreach> </select>
The collection attribute names the parameter to iterate (with special values like list or array used for single collection/array parameters, or a named property for object/map parameters), item names the variable representing each element within the loop body, and open/close/separator control the wrapping characters and delimiter joining each repetition.
Internally, MyBatis expands the <foreach> element into a series of individual #{} placeholders — one per collection item — before the statement is sent to the database, meaning each item still goes through safe, parameterized binding rather than raw string concatenation, which is what keeps a foreach-generated IN clause safe from SQL injection even though its size varies dynamically based on the input collection's length.
More Related questions...