我想使用 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 获取连接。
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();
关于java - 在 Hibernate 中使用 Native SQL 批量插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25419488/