SpringBoot JPA批处理

版权声明:本文为博主书香代码原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010138825/article/details/83095378
/**
* 批量处理
*
*/
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();
        }
    }
}

展开阅读全文

没有更多推荐了,返回首页