From《MyBatis从入门到精通》
一、foreach实现in集合
1.映射文件中添加的代码:
2.接口类中添加的方法:
ListselectByIdList(List idList);
3.测试代码
@Test public void testSelectByIdList(){ SqlSession sqlSession = getSqlSession(); try{ UserMapper userMapper=sqlSession.getMapper(UserMapper.class); ListidList = new ArrayList (); idList.add(1L); idList.add(1001L); List userList = userMapper.selectByIdList(idList); Assert.assertEquals(2,userList.size()); }finally { sqlSession.close(); } }
二、foreach实现批量插入
1.映射文件中添加的代码:
insert into sys_user( user_name,user_password,user_email, user_info,head_img,create_time) values ( #{user.userName},#{user.userPassword},#{user.userEmail}, #{user.userInfo},#{user.headImg,jdbcType=BLOB}, #{user.createTime,jdbcType=TIMESTAMP} )
2.接口类中添加的方法:
int insertList(ListuserList);
3.测试代码:
@Test public void testInsertList() { SqlSession sqlSession = getSqlSession(); try{ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); ListuserList = new ArrayList (); for (int i = 0; i < 2; i++) { SysUser user = new SysUser(); user.setUserName("test"+i); user.setUserPassword("123456"); user.setUserEmail("test@mybatis.tk"); userList.add(user); } int result = userMapper.insertList(userList); Assert.assertEquals(2,result); }finally { sqlSession.rollback(); sqlSession.close(); } }
三、foreach实现动态UPDATE
1.映射文件中添加的代码:
update sys_user set ${key}=#{val} where id=#{id}
2.接口类中添加的方法:
int updateByMap(Mapmap);
3.测试代码:
@Test public void testUpdateByMap(){ SqlSession sqlSession = getSqlSession(); try{ UserMapper userMapper=sqlSession.getMapper(UserMapper.class); Mapmap=new HashMap (); map.put("id",1L); map.put("user_email","test@mybatis.tk"); map.put("user_password","1234456"); userMapper.updateByMap(map); SysUser user = userMapper.selectById(1L); Assert.assertEquals("test@mybatis.tk",user.getUserEmail()); } finally { sqlSession.rollback(); sqlSession.close(); } }