你插入数据库数据的姿势对么?

问题来源

对于数据库操作,不可避免会出现大数据插入的场景,而对于数据库而言
1、一次插入数据过多,sql 语句过长会报错
2、一次插入数据过多,导致长事务,不利于并发操作。
因此,需要一个将数据批量插入的工具类类辅助。那么,如果实现一个通用的工具类,你不妨可以思考下。

解决办法

利用 java8 的 Function 可以做得非常简洁通用

public class BatchUtils {
    /**
     * 批量执行
     *
     * @param datas
     * @param function
     * @param <T>
     * @return
     */
    public static <T> int batchExec(List<T> datas, Function<List<T>, Integer> function) {
        return batchExec(datas, 500, function);
    }

    /**
     * 批量执行
     *
     * @param datas
     * @param batchSize
     * @param function
     * @param <T>
     * @return
     */
    public static <T> int batchExec(List<T> datas, int batchSize, Function<List<T>, Integer> function) {
        int count = 0;
        int size = datas.size();
        for (int index = 0; index < size; index += batchSize) {
            if (index + batchSize <= datas.size()) {
                count += function.apply(datas.subList(index, index + batchSize));
            } else {
                count += function.apply(datas.subList(index, size));
            }
        }
        return count;
    }

    public static void main(String[] args) {
        List<Integer> datas = new ArrayList();
        for (int i = 0; i < 100; i++) {
            datas.add(i);
        }
        System.out.println(batchExec(datas, 10, (item) -> item.size()));;
        System.out.println(batchExec(datas, 9, (item) -> item.size()));;
        System.out.println(batchExec(datas, 15, (item) -> item.size()));;
    }
}	

总结

实现是不是很简单通用呢?如果你有更好的办法,欢迎留言讨论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值