hibernate批量插入

  // 从hibernate获取连接,并用doWork进行原声jdbc操作,这样事务管理机制就是使用的一个Transaction
        Transaction transaction = null;
        Session currentSession = null;
        try {
            currentSession = this.getSessionFactory().getCurrentSession();
            transaction = currentSession.getTransaction();
            currentSession.doWork(new Work() {
                @Override
                public void execute(Connection connection) throws SQLException {
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
//业务逻辑处理
                    for (Integer carId : carIds) {
                        preparedStatement.setInt(1,primaryKeyId);
                        preparedStatement.setInt(2,carId);
                        preparedStatement.addBatch();
                    }
                    preparedStatement.executeBatch();
                }
            });
//            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
            throw new SQLException();
        }finally {
        }

 

posted @ 2018-11-06 19:48  缘来是妳啊  阅读(39)  评论(0编辑  收藏  举报