测试数据库为mysql,grails-3.1.5,hibernate4,执行效率为1W/8秒左右。
package com.system import grails.transaction.Transactional @Transactional(readOnly = true) class TestController { def sessionFactory @Transactional def save() { println "开始执行:"+new Date().format("yyyy-MM-dd HH:mm:ss") def time = System.currentTimeMillis() (1..50000).each {counter-> Test t = new Test() t._name="张三" t._age="20" t._sex="男" t._addrs="重庆市" t.save() if(counter.mod(100)==0) { sessionFactory.currentSession.flush(); sessionFactory.currentSession.clear(); } if(counter.mod(10000)==0) { Date endTime =new Date() println "插入"+counter+"条数据,耗时:"+((System.currentTimeMillis()-time)/1000) } } println "结束执行:"+new Date().format("yyyy-MM-dd HH:mm:ss") render "执行完成" } }
class TestController { def dataSource @Transactional def save() { def time = System.currentTimeMillis() def sql = new Sql(dataSource) for(int i=0;i<500000;i++) { def id = (i+1) def title = "测试:"+(i+1) def url = "http://www.baidu.com"+(i+1) sql.withBatch {stmt-> stmt.addBatch("insert into test(id,version,title,url) values('"+id+"','0','"+title+"','"+url+"');") stmt.executeBatch() } } sql.close() println "插入50万条数据,耗时:"+((System.currentTimeMillis()-time)/1000) render "插入50万条数据,耗时:"+((System.currentTimeMillis()-time)/1000) } }效果:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!