我想使用Hibernate Native sql在数据库中插入记录.代码如下所示
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String sqlInsert = "insert into sampletbl (name) values (?) "; for(String name : list){ session.createsqlQuery( sqlInsert ) .setParameter(1,name) .executeUpdate(); } tx.commit(); session.close();
解决方法
Hibernate有一个批处理功能.但在上面的例子中,我使用的是Native sql,根据我的观察,hibernate批处理对于Native sql来说效果不是很好.是的,它确实避免了内存不足错误,但没有提高性能.
因此我退回到在Hibernate中实现了JDBC Batch.Hibernate提供了方法doWork()来从Hibernate Session获取Connection.
因此我退回到在Hibernate中实现了JDBC Batch.Hibernate提供了方法doWork()来从Hibernate Session获取Connection.
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); //get Connction from Session session.doWork(new Work() { @Override public void execute(Connection conn) throws sqlException { PreparedStatement pstmt = null; try{ String sqlInsert = "insert into sampletbl (name) values (?) "; pstmt = conn.prepareStatement(sqlInsert ); int i=0; for(String name : list){ pstmt .setString(1,name); pstmt .addBatch(); //20 : JDBC batch size if ( i % 20 == 0 ) { pstmt .executeBatch(); } i++; } pstmt .executeBatch(); } finally{ pstmt .close(); } } }); tx.commit(); session.close();