Original source: http://blog.csdn.net/qh_java/article/details/50754271
In the configuration file of mybatis, we often use collection arrays and batch queries of maps, so we will often use foreach. First, let's take a look at the properties of foreach:
This picture is very well written, it's good, that's it, you know...
Knowing these properties, let's take a look at the small demo:
1. List<Integer> IntList and List<String> strList collections store basic types
- <select id="dynamicForeachTest" parameterType="java.util.List" resultMap="Users">
- select id,name from t_blog where id in
- <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
2. List<Obect> objList , List<Users> userList reference type data
- package soufun.com;
- /**
- *@author WHD
- *data February 27, 2016
- */
- publicclass Users {
- privateint id;
- private String name;
- publicint getId() {
- return id;
- }
- publicvoid setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- publicvoid setName(String name) {
- this.name = name;
- }
- }
- <select id="dynamicForeachTest" parameterType="java.util.List" resultMap="Users">
- select id,name from t_blog where id in
- <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
- #{item.id}
- </foreach>
- </select>
循环插入
- insert into t_blog(id,name) values
- <foreach collection="list" item="item" index="index" separator=",">
- (#{item.id},#{item.name})
- </foreach>
到这里都结束了,但还有个小事说一下,那就是in 的那个遍历,一般我们都是使用foreach 来组装 的但是有看到这样写的:
String name ="'w1','w2','w3','w4'";
- <select id="getByMap" resultMap="Users">
- SELECT * FROM t_blog where name in (${name})
- </select>
3. The use of Map, if Map is used as a parameter, the processing method is the same as passing a basic variable and direct reference is ok.
- <select id="selectjdnotconfirmorder" parameterType="java.util.Map" resultMap="result">
- select bzOrderId,jdOrderId,name,mobile,success from jdorderinfo where jdIsOrder = ${notSubmit} and success =${success}
- </select>
- Map<String,Integer> hashMap= new HashMap<String,Integer>();
- hashMap.put("notSubmit", notSubmit);
- hashMap.put("success", state);
4. The difference between # and $ in mybatis, the variable of # is with single quotation marks and $ is without single quotation marks, for example, the two variables of notSubmit and success above are int type, so instead of # but $, because are numbers instead of characters.