mybatis的foreach插入List,Array,Map
阿新 • • 發佈:2019-02-06
list儲存
1、xml檔案
<!-- 儲存List-->
<insert id="saveList" parameterType="java.util.List">
INSERT INTO user_info(id,username,password) VALUES
<foreach collection="list" item="userinfo" separator=",">
(#{userinfo.id}, #{userinfo.username}, #{userinfo.password})
</foreach >
</insert>
2、mapper
void saveList(List<UserInfo> userInfos);
Array儲存
1、xml檔案
<!-- 儲存List-->
<insert id="saveArray" parameterType="java.util.List">
INSERT INTO user_info(id,username,password) VALUES
<foreach collection="array" item="userinfo" separator =",">
(#{userinfo.id}, #{userinfo.username}, #{userinfo.password})
</foreach>
</insert>
2、mapper
void saveArray(UserInfo[] userInfos);
Map儲存
1、xml
<!-- 儲存Map-->
<insert id="saveMap" parameterType="java.util.Map">
INSERT INTO user_info
<foreach collection="userInfoMap.keys" item="key" separator="," open="(" close=")">
${key}
</foreach>
VALUES
<foreach collection="userInfoMap.keys" item="userValue" separator="," open="(" close=")">
#{userInfoMap[${key}]}
</foreach>
</insert>
2、map
void saveMap(@Param("userInfoMap")Map<String,Object> userInfoMap);
測試程式碼:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Transactional
@SpringBootTest(classes = Application.class)
public class UserTest {
@Autowired
private UserInfoMapper userInfoMapper;
private List<UserInfo> initUserList(){
List<UserInfo> userInfoList = new ArrayList<>();
for (int i = 210; i < 211; i++){
UserInfo userInfo = new UserInfo();
userInfo.setId(i);
userInfo.setUsername("zzr"+i);
userInfo.setPassword("zzr"+i);
userInfoList.add(userInfo);
}
return userInfoList;
}
private UserInfo[] initUserArray(){
List<UserInfo> userInfoList = initUserList();
UserInfo[] userInfos = new UserInfo[userInfoList.size()];
int i = 0;
for (UserInfo userInfo : userInfoList){
userInfos[i++] = userInfo;
}
return userInfos;
}
/**
* 儲存List
*/
@Test
public void saveList(){
userInfoMapper.saveList(initUserList());
}
/**
* 儲存陣列
*/
@Test
public void saveArray(){
userInfoMapper.saveArray(initUserArray());
}
/**
* 儲存map
*/
@Test
public void saveMap(){
Map map = new HashMap();
map.put("id",1000);
map.put("username",1000);
map.put("password",1000);
userInfoMapper.saveMap(map);
}
}