For reasons, not needed to divulge, I need to run a series of native SQL statements using the hibernate layer. They are the same statement (same bind variables) of the form "insert abc(column1,column2) values(:column1List, :column2List)".
I would like to execute this as a batch insert if possible. Can it be done ? If so how ?
I tried sqlQuery = session.createSQLQuery(sqlQuery); sqlQuery.setParameterList(.....)
sqlQuery = session.createSQLQuery(sqlQuery); sqlQuery.setParameterList(.....)
I think I found out the reason but I am not sure what's happening. The insert statement has more than 2 columns and hibernate is changing it into insert into abc(column1, column2, column3, column4,column5, column6) values ( ?,?, (?,?),(?,?),(?,?),?)
You would probably want to look at using JDBC for batch inserts, this will strip out the overheads associated with hibernate and allows you to work off a list of predefined parameters
import java.sql.Connection;
import java.sql.PreparedStatement;
//...
String sql = "insert into employee (name, city, phone) values (?, ?, ?)";
org.hibernate.Session sess = (org.hibernate.Session) em.getDelegate();
Connection conn = sess.connection();
PreparedStatement ps = connection.prepareStatement(sql);
for (Employee employee: employees) {
ps.setString(1, employee.getName());
ps.setString(2, employee.getCity());
ps.setString(3, employee.getPhone());
ps.addBatch();
}
ps.executeBatch();
ps.close();
connection.close();
Example taken from ( http://viralpatel.net/blogs/batch-insert-in-java-jdbc/ )
I am on hibernate 4.1.4. I tried every trick I can think of to make it work. Hence I am on hibernate 4. I had to resort to implementing a class that did work "org.hibernate.jdbc.Work". Once I have a statement handle, everything went smooth and I got my answer. The approach is correct outlined by DaveB.
Transaction tx = session.beginTransaction() ;
SqlWork sqlWork = new SQLWork(a,b,c) ; // used inside execute <br/>
session.doWork(sqlWork) ;
tx.commit();
} catch (HibernateException he) {
tx.rollback();
} finally {
session.close()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.