mybatis批量数据操作
原文:http://www.cnblogs.com/sunwufan/archive/2012/04/27/2473308.html
1) simple方式(基本数据库逐条访问)
a) 通过for循环
Person per = new Person();
for (int i = 1; i <= num; i++) {
sqlSession.insert("org.wufan.dao.PersonDao.insert", per);
sqlSession.commit();
}
2) batch方式(批量操作)
Map<String, List<Person>> tmp = new HashMap<String, List<Person>>();
tmp.put("persons", list);
sqlSession.insert("org.wufan.dao.PersonDao.insertBatch", tmp);
sqlSession.commit();
sql映射文件:
<insert id="insertBatch" parameterType="org.wufan.vo.Person"
keyProperty="id" keyColumn="GENERATED_KEY" useGeneratedKeys="true">
INSERT INTO person ( name, age, sex, password)
VALUES
<foreach collection="persons" item="item" index="index"
separator=",">
(#{item.name},#{item.age},#{item.sex},#{item.password})
</foreach>
</insert>
3) procedure方式(存储过程)
Map map = new HashMap();
map.put("name", "InsertProcName");
map.put("age", 11);
map.put("sex", "男");
map.put("password", "1234");
map.put("num", num);
double begin = System.currentTimeMillis();
sqlSession.insert("org.wufan.dao.PersonDao.insertByProc", map);
sqlSession.commit();
sql映射文件:
<insert id="insertByProc" statementType="CALLABLE">
{call insertProc(#{name},#{age},#{sex},#{password},#{num})}
</insert>

浙公网安备 33010602011771号