一、平时用到List、array[数组]的情况比较多,工作中有一个需求,想到可以用map来传值,而且比较方便,把我的场景分享给大家。
二、
场景1:insert时,列的数量和名称是不固定的,需要动态的处理,这种需求感觉用map传值比较方便。
场景2:
1 单元测试:
@RunWith(SpringJUnit4ClassRunner.class)//junit整合spring的测试//立马开启了spring的注解
@ContextConfiguration(locations="classpath:spring/application*.xml")//加载核心配置文件,自动构建spring容器
public class Start1 {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert(){
Map<String,Map<String,Object>> param = new HashMap<String,Map<String,Object>>();
Map<String,Object> map = new HashMap<String,Object>();
map.put("id", null);
map.put("user_name", "testname");
map.put("password", "1234556");
map.put("name", "test");
map.put("age", 10);
map.put("birthday", "2018-08-31");
map.put("created", "2018-08-31");
map.put("updated", "2018-08-31");
param.put("keys", map);
int count = this.userMapper.insertUser(param);
System.out.println(count);
}
@Test
public void testInserts(){
Map<String,List<Object>> param = new HashMap<String,List<Object>>();
List<Object> l = new ArrayList<Object>();
User u1 = new User();
u1.setUserName("u1_name");
u1.setPassword("11111");
u1.setName("u1");
u1.setSex(1);
u1.setAge(20);
u1.setCreated(new Date());
u1.setBirthday(new Date());
u1.setUpdated(new Date());
User u2 = new User();
u2.setUserName("u2_name");
u2.setPassword("11111");
u2.setName("u2");
u2.setSex(1);
u2.setAge(20);
u2.setCreated(new Date());
u2.setBirthday(new Date());
u2.setUpdated(new Date());
l.add(u1);
l.add(u2);
param.put("keys", l);
int count = this.userMapper.insertUsers(param);
System.out.println("..............."+count);
}
}
2 Mapper接口
public interface UserMapper {
//如果使用@param("xxx")注解的话,foreach集合中的colleciton的值可以是"xxx.keys"
public int insertUser(Map> param);
public int insertUsers(Map> param);
}
3 mapper.xml文件
<insert id="insertUser" parameterType="map">
insert into tb_user
<foreach collection="keys" index="key" item="value" open="(" close=")" separator=",">
${key}
foreach>
values
<foreach collection="keys" item="value1" open="(" close=")" separator=",">
#{value1}
foreach>
insert>
<insert id="insertUsers">
insert into tb_user
( id, user_name, password,sex,
name, age, birthday, created, updated)
values
<foreach collection="keys" item="value" separator=",">
(null,#{value.userName},#{value.password},#{value.sex},#{value.name},#{value.age},#{value.birthday},#{value.created},#{value.updated})
foreach>
insert>
三、 foreach 中的参数详解
场景1中的foreach
四、转载的图(文字说明)
此图转自:https://blog.csdn.net/d729332647/article/details/80985812