Location>code7788 >text

The use of foreach in Mybatis

Popularity:689 ℃/2024-11-19 23:54:49
The first thing we need to understand is that the essence of foreach is the database can execute the sql in xml in accordance with a certain syntax to splice, so before splicing, we understand the role of foreach tag in several common elements

List or Array: If the passed parameter type is List or Array. the default value of the collection property is list and array respectively. if you need to customize the name of the collection.
Map: If the passed parameter is a Map, the collection attribute can be specified to traverse the keys, values or entrySet of the Map.

Alias for each element in a set traversal

Top spliced strings when splicing sql

Separation string between two elements when splicing sql

The last string to splice when splicing the sql.

index: in List or Array, index is the index of the element; in Map, index is the key value of the traversed element.
A simple example
A simple sql
select * from blog where title is not null and (id=1 or id=2 or id=3)
1. We use the map collection as a parameter to implement the splice
<select parameterType="map" resultType="blog"> select * from blog <where> title is not null <foreach collection="ids" item="id" open="and (" separator="or" close=")"> id=#{id} </foreach> </where> </select>
2. We use the list collection as a parameter to implement the splice