JDBC中在做数据插入、更新、删除操作,可以使用executeBatch()方法减少数据库调用次数,如:
Statement pstmt = conn.createStatement(); pstmt.addBatch("insert into settings values(3,'小米','女')"); pstmt.addBatch("insert into settings values(4,'小李','女')"); pstmt.addBatch("insert into settings values(5,'小王','男')"); pstmt.addBatch("insert into settings values(6,'小明','男')"); pstmt.executeBatch();
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Student entity = new Student(.....); session.save(entity); if ( i % 50 == 0 ) { //每次批量把50条数据写入数据库并释放内存 session.flush(); session.clear(); } } tx.commit(); session.close();
<insert id ="insertBatch" parameterType="List" > insert into STUDENT( ID,NAME,SEX) values <foreach collection ="list" item ="item" index ="index" separator =","> ( #{item.id},#{item.name},#{item.sex}) </foreach> </insert >