CRMEB 基础 列表拖动排序1

前端排序代码

    <script>
        // 原文:https://blog.csdn.net/funche/article/details/106308936
        var arr = [
            {
                id: 0,
                name: 'Tom0'
            }, {
                id: 1,
                name: 'Tom1'
            }, {
                id: 2,
                name: 'Tom2'
            }, {
                id: 3,
                name: 'Tom3'
            }, {
                id: 4,
                name: 'Tom4'
            }
        ]

        // 把 Tom0 跟 Tom3 位置对调
        var sourceIndex = 0        
        var targetIndex = 3

        arr[sourceIndex] = arr.splice(targetIndex, 1, arr[sourceIndex])[0]

        console.log(arr);
    </script>

后端排序代码


	/**
	 * 排序保存
	 *
	 * @param entities
	 * @return
	 */
	public boolean saveSort(List<T> entities) {

		if (entities.size() <= 0) {
			throw new ServiceException("数据不能为空");
		}

		List<Long> ids = entities.stream().map(c -> c.getId()).collect(Collectors.toList());

		// 数据库中 根据sort排序后 的原始数据
		List<T> items = listByIds(ids)
			.stream()
			.sorted(Comparator.comparing(T::getSort))
			.collect(Collectors.toList());

		// 前端传入的 根据索引排序后的数据 与数据库的数据 根据索引一一对应,然后改变其sort
		for (int i = 0; i < entities.size(); i++) {
			entities.get(i).setSort(items.get(i).getSort());
		}

		// 只改变数据库数据的sort字段
		for (T item : items) {
			T entity = entities.stream()
				.filter(c -> item.getId().equals(c.getId()))
				.findFirst()
				.orElse(null);

			if (Objects.nonNull(entity)) {
				item.setSort(entity.getSort());
			}
		}

		return updateBatchById(items);
	}

原文地址:https://www.cnblogs.com/guxingy/p/15330985.html