带有自动切割功能的批量保存方法

前言

现在做的是一个数据分析平台,每个项目的元数据配置都不一样
然后来了个新需求是,要求克隆某个项目生成一个新项目
这个情况下需要写大量的saveBatch
很多保存的时候都无法确定数量,那么就有可能因为达到sql长度而报错

通过我下面这套函数式接口,写起来不要太轻松

代码正文

	interface SaveBatch<T>{
		void apply(List<T> list);
	}

	private <T> void insertBatch(List<T> listObj, SaveBatch<T> function){
		List<List<T>> lists = partition(listObj, 100);
		for(List<T> list:lists){
			function.apply(list);
		}
	}

	public static <T> List<List<T>> partition(final List<T> list, final int size) {
		if (list == null) {
			throw new NullPointerException("List must not be null");
		}
		if (size <= 0) {
			throw new IllegalArgumentException("Size must be greater than 0");
		}
		return new Partition<>(list, size);
	}

	private static class Partition<T> extends AbstractList<List<T>> {
		private final List<T> list;
		private final int size;

		private Partition(final List<T> list, final int size) {
			this.list = list;
			this.size = size;
		}

		@Override
		public List<T> get(final int index) {
			final int listSize = size();
			if (index < 0) {
				throw new IndexOutOfBoundsException("Index " + index + " must not be negative");
			}
			if (index >= listSize) {
				throw new IndexOutOfBoundsException("Index " + index + " must be less than size " +
						listSize);
			}
			final int start = index * size;
			final int end = Math.min(start + size, list.size());
			return list.subList(start, end);
		}

		@Override
		public int size() {
			return (int) Math.ceil((double) list.size() / (double) size);
		}

		@Override
		public boolean isEmpty() {
			return list.isEmpty();
		}
	}
	
	//用例
	insertBatch(newProjectKanBans,kanBanMapper::saveKanBanBatch);