Java将Spring数据排序转换为比较器

问题描述 投票:0回答:1

我构建了一个Spring Boot应用程序,该应用程序使用Spring Data Sort类对数据库中的实体进行排序。但是,出于一致性的原因,我还想将这种排序机制应用于一般列表或流,因此需要将其转换为Comparator

我想出了一个解决方案,但我觉得有一种更优雅和/或类型安全的方法。有什么建议吗?

import org.springframework.data.domain.Sort;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Comparator;
import java.util.Iterator;

public class ComparatorUtils {
    public static <T> Comparator<T> convert(Sort sort, Class<T> type) {
        final Iterator<Sort.Order> orderIterator = sort.iterator();
        final Sort.Order order = orderIterator.next();

        Comparator<T> comparator = convert(order, type);
        while (orderIterator.hasNext()) {
            comparator = comparator.thenComparing(convert(orderIterator.next(), type));
        }

        return comparator;
    }

    private static <T> Comparator<T> convert(Sort.Order order, Class<T> type) {
        Comparator<T> comparator = Comparator.comparing((T entity) -> {
            try {
                return (Comparable) new PropertyDescriptor(order.getProperty(), type).getReadMethod().invoke(entity);
            } catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
                throw new RuntimeException(e);
            }
        });

        if (order.isDescending())
            return comparator.reversed();
        return comparator;
    }
}
java spring spring-data comparator
1个回答
0
投票
  • 我更喜欢在其中缓存描述符的org.springframework.beans.BeanUtils.getPropertyDescriptor(而不是新的PropertyDescriptor)。
  • 此解决方案也缺少按较深字段排序(例如Person.Address.Street)

但是对于弹簧数据维护者来说,这是一个很好的问题。还没有用于此目的的工具吗?

© www.soinside.com 2019 - 2024. All rights reserved.