Batch insert using Native SQL in Hibernate

前端 未结 3 1509
盖世英雄少女心
盖世英雄少女心 2020-12-24 08:51

I want to insert records in database using Hibernate Native SQL.The code is like below

 Session session = sessionFactory.openSession();
 Transaction tx = ses         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 09:35

    Here is the same example for 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 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);
                }
            });
        }
    }
    

提交回复
热议问题