How to use the foreach statement in MyBatis?

The foreach statement in MyBatis is used to loop through a collection or array in dynamic SQL. It allows you to repeatedly execute the same SQL fragment multiple times in the SQL statement, each time using an element from the collection or array.

Here is an example of using the MyBatis foreach statement:

  1. Define the foreach statement in the XML mapping file.
<select id="getUsersByIds" resultType="User">
  SELECT * FROM users WHERE id IN
  <foreach item="item" collection="ids" open="(" separator="," close=")">
    #{item}
  </foreach>
</select>

In the above example, we are using a foreach statement to iterate through a collection named ids in an SQL query.

  1. Set collection in Java code.
List<Integer> ids = Arrays.asList(1, 2, 3);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("ids", ids);
List<User> users = sqlSession.selectList("getUsersByIds", paramMap);

In the example above, we created a List named ids and passed it as a parameter to the selectList method of MyBatis.

This is the basic usage of the foreach statement in MyBatis. You can customize the settings based on your needs, such as specifying the name of the elements in the collection, setting the beginning and ending strings of the loop, and specifying the delimiter between loop elements, and so on.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds