mybatis-批量操作

阅读更多

代码如下:

 

1、获取sqlSession

/**
	 * 使用XML配置文件获取sqlsession
	 * @return
	 */
	public static SqlSession createSqlSessionByXML(){
		//获取config.xml文件
		String resource = "conf/config.xml";
		InputStream input = null;
		try {
			input = Resources.getResourceAsStream(resource);
			//获得sqlsession
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input);
			session = factory.openSession();
			return session;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

 

2、批量插入

 

/**
	 * 批量增加
	 */
	//@Test
	public void insertBatch(){
		
		List users = new ArrayList();
		for(int i=0;i <= 20;i++){
			User user = new User("姓名"+i, i%2, i+20);
			users.add(user);
		}
		
		//使用xml配置执行
		try{
			session = SessionUtil.createSqlSessionByXML();
			//使用mapper.xml文件执行
			User user = session.selectOne("org.mybatis.UserMapper.insertBatch",users);
		}finally{
			session.close();
		}
	}

//xml配置;


	
       insert into user(name,sex,age) values
    	
	       (#{item.name}, #{item.sex},#{item.age})
    	
 	

 

2、批量更新

 

/**
	 * 批量更新
	 */
	//@Test
	public void updateBatch(){
		
		Map map = new HashMap();
		List idlist = new ArrayList();
		for(int i=0;i<10;i++){
			idlist.add(i+45);
		}
		map.put("idlist", idlist);
		map.put("name", "姓名x");
		
		//使用xml配置执行
		try{
			session = SessionUtil.createSqlSessionByXML();
			//使用mapper.xml文件执行
			User user = session.selectOne("org.mybatis.UserMapper.updateBatch",map);
		}finally{
			session.close();
		}
	}

//xml 文件配置

 	
	    update user
	    set name = #{name} where id in
	    
	            #{ uid}
	     
    

 

3、批量删除

 

/**
	 * 批量删除
	 */
	@Test
	public void deleteBatch(){
		
		List idList = new ArrayList();
		for(int i=0;i <= 5;i++){
			idList.add(i);
		}
		
		//使用xml配置执行
		try{
			session = SessionUtil.createSqlSessionByXML();
			//使用mapper.xml文件执行
			User user = session.selectOne("org.mybatis.UserMapper.deleteBatch",idList);
		}finally{
			session.close();
		}
	}

//xml文件配置

      
	    DELETE FROM user WHERE id IN  
	       
	        #{item}   
	      
	

 

 

操作过程成偶然报错误:

 

org.apache.ibatis.exceptions.PersistenceException: 

### Error querying database.  Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for org.mybatis.UserMapper.updateBatch

### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for org.mybatis.UserMapper.updateBatch

at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26)

 

 

该错误大意就是,*mapper.xml未找到或里面的sql中跟mapper接口中的方法不对应。我因为在xml文件中的id,与session.selectOne("org.mybatis.UserMapper.deleteBatch",idList)的方法不符合,造成该错误

你可能感兴趣的:(mybatis,批量,insert,update,delete)