-
MyBatis foreach Tag Explained | Iterate List, Array, Map with key and valueBrawny Develop/EN_Practical Development Basics_Query 2025. 7. 8. 15:42
When working with MyBatis, iterating over collections like Lists, arrays, or Maps in SQL statements is a common requirement. MyBatis provides the <foreach> tag, which makes handling these collections straightforward and efficient.
The <foreach> tag allows you to loop through a collection and generate SQL snippets dynamically, such as building IN clauses or batch inserts.
Here’s what you need to know about using <foreach> with different collection types:
- List and Array: The most common usage is iterating over Lists or arrays. You specify the collection attribute with the name of the parameter, and item as the variable representing each element.
- Map: When you pass a Map as a parameter, you can iterate over its entries. Use the index attribute to get the key and item for the value.
- Key and Value: index represents the key in a Map or the current index in a List/array. item represents the value at that position.
Basic usage example:
Using Map:
Important notes:
- Make sure the collection attribute matches the parameter name you pass from Java.
- The open, separator, and close attributes help to format SQL properly (e.g., parentheses and commas).
- For Maps, use index for the key and item for the value.
- The <foreach> tag is powerful for batch operations and dynamic SQL building.
This tag greatly simplifies working with collections in MyBatis SQL mappings and improves code readability and maintainability.'Brawny Develop > EN_Practical Development Basics_Query' 카테고리의 다른 글