1. 程式人生 > >SpringBoot JPA批處理

SpringBoot JPA批處理

/**
* 批量處理
*
*/
public interface JpaBatch<T> {
}


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

public abstract class JpaInsertBatch<T> implements JpaBatch {

    private static final Logger logger = LoggerFactory.getLogger(JpaInsertBatch.class);

    @PersistenceContext
    protected EntityManager em;

    @Transactional
    public void batchInsert(List list) {
        try {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                em.persist(list.get(i));
                if (i % 1000 == 0 || i == (size - 1)) {//一次一千條插入
                    em.flush();
                    em.clear();
                }
            }
            logger.info("入庫成功,共 {}條資料", list.size());
        } catch (Exception e) {
            logger.error("批量插入失敗");
            e.printStackTrace();
        }
    }
}