SpringBoot JPA批处理

/**
* 批量处理
*
*/
public interface JpaBatch {
}


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 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();
        }
    }
}

你可能感兴趣的:(JPA,Java,Why)