溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

JPA如何批量保存saveAll

發(fā)布時(shí)間:2022-01-14 09:22:47 來(lái)源:億速云 閱讀:1867 作者:小新 欄目:大數(shù)據(jù)

這篇文章將為大家詳細(xì)講解有關(guān)JPA如何批量保存saveAll,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

使用了JPA的saveAll方法批量保存一千多條數(shù)據(jù)的問(wèn)題,但是發(fā)現(xiàn)日志打印卻是一條一條的insert語(yǔ)句。

JPA如何批量保存saveAll

查看saveAll的源碼,發(fā)現(xiàn)里面是使用了一個(gè)for循環(huán)然后一條條的執(zhí)行save方法....

JPA如何批量保存saveAll

好吧,手動(dòng)寫(xiě)一個(gè)批量執(zhí)行的方法

@Component
public class DbUtils {

    private static EntityManager entityManager;

    public static final int BATCH_SIZE = 1000;

    public static EntityManager getEntityManager() {
        if (entityManager == null) {
            entityManager = SpringUtils.getBean(EntityManager.class);
        }
        return entityManager;
    }

    public static void setEntityManager(EntityManager entityManager) {
        //DbUtils.entityManager = entityManager;
    }

    public static void batchExecute(String sql, List<Object[]> params, Integer batchSize){
        if (batchSize == null) {
            batchSize = BATCH_SIZE;
        }
        if(params.size() == 0){
            return;
        }
        Connection conn = null;
        Session session = null;
        PreparedStatement stmt = null;
        try {
            session = (Session) getEntityManager().getDelegate();
            SessionFactoryImpl sf = (SessionFactoryImpl)session.getSessionFactory();
            conn = sf.getJdbcServices().getBootstrapJdbcConnectionAccess().obtainConnection();
            stmt = conn.prepareStatement(sql);
            conn.setAutoCommit(false);
            int index = 0;
            for (Object[] objects : params) {
                for(int i=0 ; i<objects.length ; i++){
                    stmt.setObject(i+1, objects[i]);
                }
                stmt.addBatch();
                index++;
                if (index % batchSize == 0){
                    stmt.executeBatch();
                    stmt.clearBatch();
                }
            }
            if (index % batchSize != 0){
                stmt.executeBatch();
                stmt.clearBatch();
            }
            conn.commit();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }finally {
            try {
                stmt.close();
                conn.close();
            }catch (SQLException e){
                throw new RuntimeException(e.getMessage());
            }
        }
    }
}

關(guān)于“JPA如何批量保存saveAll”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

jpa
AI