/**
* 批量增加
*/
//@Test
public void insertBatch(){
List<User> users = new ArrayList<User>();
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 id="insertBatch" >
insert into user(name,sex,age) values
<foreach collection="list" item= "item" index ="index" separator=",">
(#{item.name}, #{item.sex},#{item.age})
</foreach >
</insert>
2、批量更新
/**
* 批量更新
*/
//@Test
public void updateBatch(){
Map<String,Object> map = new HashMap<String,Object>();
List<Integer> idlist = new ArrayList<Integer>();
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 id= "updateBatch" parameterType= "map">
update user
set name = #{name} where id in
<foreach collection="idlist" item= "uid" index ="index"
open= "(" close =")" separator=",">
#{ uid}
</foreach >
</update >
3、批量删除
/**
* 批量删除
*/
@Test
public void deleteBatch(){
List<Integer> idList = new ArrayList<Integer>();
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 id="deleteBatch" parameterType="java.util.List">
DELETE FROM user WHERE id IN
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
操作过程成偶然报错误:
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)的方法不符合,造成该错误