Six Attributes
- collection: There are three formats: list, array, and map, according to the type of parameter passed.
- item: the parameter name of the set of objects in the tag.
- separator: the separator at the end of each sub-loop, usually “,”.
- open: start character, often “(“.
- close: end character, often “)”.
- index: index refers to the index of element in lists and arrays, ; but in maps, index refers to the key of the element, incremented from 0 (equivalent to an array subscript).
Scenarios for the application of <foreach>
1. Batch Insert
INSERT INTO table (a, b, c, d) VALUES
<foreach collection = "list" item = "item" separatior = ",">
(#{item.a}, #{item.b}, #{item.c}, #{item.d})
</foreach>
// This sql will be generated:
INSERT INTO table (a, b, c, d) VALUES
('a',123,true,'112456789'),
('b',124,true,'112455789'),
('c',125,false,'112466789'),
('d',126,true,'112451789')
2. Batch Update
UPDATE table SET b = '10'
WHERE a IN
<foreach collection = "list" item = "item" open = "(" close = ")" separator = ",">
#{item.a}
</foreach>
UPDATE table
SET a =
CASE
<foreach collection="list" item="item">
WHEN b=#{item.b} AND c = #{item.c} THEN '10'
</foreach>
ELSE a END;
3. Batch Query
SELECT * FROM table
WHERE a IN
<foreach collection = "list" item = "item" open = '(' close = ')' separator = ','>
#{item.a}
</foreach>
SELECT * FROM table
WHERE a = #{a}
AND
<foreach collection = "list" item = "item" open = '(' close = ')' separator = 'OR'>
b = #{item.b}
AND c = #{item.c}
AND d = #{item.d}
</foreach>
0 Comments