在Hibernate中使用Native SQL批量插入

Oom*_*ity 9 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();
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常.我认为这不是最好的方法.如果有的话,请给我另一种可能的方法.谢谢

Oom*_*ity 14

Hibernate有一个批处理功能.但在上面的例子中,我使用的是Native SQL,根据我的观察,hibernate批处理对于Native SQL来说效果不是很好.是的,它确实避免了内存不足错误,但没有提高性能.因此我退回到在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();
Run Code Online (Sandbox Code Playgroud)


Geo*_*nan 6

这是Java 8,Hibernate-JPA 2.1的相同示例:

@Repository
public class SampleNativeQueryRepository {
    private final Logger log = LoggerFactory.getLogger(SampleNativeQueryRepository.class);
    @PersistenceContext
    private EntityManager em;

    public void bulkInsertName(List<String> list){
        Session hibernateSession = em.unwrap(Session.class);
        String sql = "insert into sampletbl (name) values (:name) ";
        hibernateSession.doWork(connection -> {
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                int i = 1;
                for(String name : list) {
                    preparedStatement.setString(1, name);
                    preparedStatement.addBatch();
                    //Batch size: 20
                    if (i % 20 == 0) {
                        preparedStatement.executeBatch();
                    }
                    i++;
                }
                preparedStatement.executeBatch();
            } catch (SQLException e) {
                log.error("An exception occurred in SampleNativeQueryRepository.bulkInsertName: {}", e);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)