mybatis foreach
时间: 2023-11-02 07:57:50 浏览: 37
MyBatis provides a "foreach" tag that allows you to iterate over a collection and generate dynamic SQL statements. It is useful when you need to perform batch operations or create dynamic queries based on a list of values.
You can use the "foreach" tag in MyBatis XML mapping files. Here's an example of how you can use it:
```xml
<select id="getUsersByIds" resultType="User">
SELECT * FROM users
WHERE id IN
<foreach item="id" collection="userIds" open="(" separator="," close=")">
#{id}
</foreach>
</select>
```
In this example, the "getUsersByIds" query selects all the users whose IDs are present in the "userIds" collection. The "foreach" tag iterates over the "userIds" collection and generates a comma-separated list of IDs inside the "IN" clause.
You can specify the name of the item (e.g., "id") and the name of the collection (e.g., "userIds") using the "item" and "collection" attributes, respectively. Other attributes like "open", "separator", and "close" allow you to customize the generated SQL statement.
Remember to also define the corresponding Java object and provide a method in your mapper interface that matches the query ID ("getUsersByIds" in this case) to retrieve the results.
This is just a basic example, and there are more advanced ways to use the "foreach" tag in MyBatis. Feel free to explore the MyBatis documentation for more information on its usage and options.