java - 在 Hibernate 中使用 Native SQL 批量插入

标签 java mysql hibernate

我想使用 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/

相关文章:

Java-Spring : dependency injection across bean factories in SingletonBeanFactoryLocator?

java - 如何更改创建新文件的默认目录

mysql - 在不登录的情况下更改 MySQL 密码

java - 将 Hibernate 配置为 Tomcat Apache 和 MySQL 上的 JPA 2.0 提供程序的学习资源

java - org.hibernate.exception.SQLGrammarException :Could not execute JDBC batch update

java - Hibernate GWT 集成抛出 "java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z"

java - 如何从类获取对象到服务

java - 设置属性 : Non-serializable attribute (Java Object Serialization)

mysql - 无法从 Ubuntu 计算机中安装的 Ejabberd 连接到 MySQL。 AWS-EC2

mysql - 在没有内部选择的情况下获取最低价格 ID