Spring JPA REST sort by nested property

iq0todco  于 9个月前  发布在  Spring
关注(0)|答案(6)|浏览(89)

我有实体MarketEventMarket实体有一列:

@ManyToOne(fetch = FetchType.EAGER)
private Event event;

字符串
接下来我有一个repository:

public interface MarketRepository extends PagingAndSortingRepository<Market, Long> {
}


一个投影:

@Projection(name="expanded", types={Market.class})
public interface ExpandedMarket {
    public String getName();
    public Event getEvent();
}


使用REST查询/api/markets?projection=expanded&sort=name,asc,我成功地获得了按市场名称排序的嵌套事件属性的市场列表:

{
    "_embedded" : {
        "markets" : [ {
            "name" : "Match Odds",
            "event" : {
                "id" : 1,
                "name" : "Watford vs Crystal Palace"
            },
            ...
        }, {
            "name" : "Match Odds",
            "event" : {
                "id" : 2,
                "name" : "Arsenal vs West Brom",
            },
            ...
        },
        ...
    }
}


但我需要的是获得按事件名称排序的市场列表,我尝试了查询/api/markets?projection=expanded&sort=event.name,asc,但它不起作用。我应该怎么做才能使它起作用?

vulvrdjw

vulvrdjw1#

基于Spring Data JPA文档属性表达式
.你可以在方法名中使用_来手动定义遍历点.
您可以在REST查询中使用下划线,如下所示:
/API/markets?projection=expanded&sort=event_name,asc

50few1ms

50few1ms2#

只需spring.data.‌​rest.webmvc降级为Hopper版本即可

<spring.data.jpa.version>1.10.10.RELEASE</spring.data.jpa.ve‌​rsion> 
<spring.data.‌​rest.webmvc.version>‌​2.5.10.RELEASE</spri‌​ng.data.rest.webmvc.‌​version>

projection=expanded&sort=event.name,asc // works
projection=expanded&sort=event_name,asc // this works too

字符串
感谢@Alan Hay对this question的评论
在Hopper版本中,按嵌套属性排序对我来说很好,但我确实在Ingalls版本的RC版本中遇到了以下bug。Ingalls版本的RC版本中的bug。据报道,这一问题已被修复,

vwkv1x7d

vwkv1x7d3#

我们有一个例子,当我们想按链接实体中的字段进行排序时(它是一对一的关系)。最初,我们使用基于https://stackoverflow.com/a/54517551的示例来搜索链接字段。
因此,我们的解决方案是提供自定义的排序和分页参数。下面是示例:

@org.springframework.data.rest.webmvc.RepositoryRestController
public class FilteringController {

private final EntityRepository repository;

@RequestMapping(value = "/entities",
        method = RequestMethod.GET)

public ResponseEntity<?> filter(
        Entity entity,
        org.springframework.data.domain.Pageable page,
        org.springframework.data.web.PagedResourcesAssembler assembler,
        org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler entityAssembler,
        org.springframework.web.context.request.ServletWebRequest webRequest
) {

    Method enclosingMethod = new Object() {}.getClass().getEnclosingMethod();
    Sort sort = new org.springframework.data.web.SortHandlerMethodArgumentResolver().resolveArgument(
            new org.springframework.core.MethodParameter(enclosingMethod, 0), null, webRequest, null
    );

    ExampleMatcher matcher = ExampleMatcher.matching()
            .withIgnoreCase()
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
    Example example = Example.of(entity, matcher);

    Page<?> result = this.repository.findAll(example, PageRequest.of(
            page.getPageNumber(),
            page.getPageSize(),
            sort
    ));
    PagedModel search = assembler.toModel(result, entityAssembler);
    search.add(linkTo(FilteringController.class)
            .slash("entities/search")
            .withRel("search"));
    return ResponseEntity.ok(search);
}
}

字符串
使用的Sping Boot 版本:2.3.8.RELEASE
我们也有实体的存储库,并使用投影:

@RepositoryRestResource
public interface JpaEntityRepository extends JpaRepository<Entity, Long> {
}

vsdwdz23

vsdwdz234#

您的MarketRepository可以有一个named query,如下所示:

public interface MarketRepository exten PagingAndSortingRepository<Market, Long> {
    Page<Market> findAllByEventByName(String name, Page pageable);
}

字符串
您可以使用@RequestParam从url获取name参数

ltqd579y

ltqd579y5#

这个page有一个可行的想法。这个想法是在仓库顶部使用一个控制器,并单独应用投影。
下面是一段可以工作的代码(SpringBoot 2.2.4)

import ro.vdinulescu.AssignmentsOverviewProjection;
import ro.vdinulescu.repository.AssignmentRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RepositoryRestController
public class AssignmentController {
    @Autowired
    private AssignmentRepository assignmentRepository;

    @Autowired
    private ProjectionFactory projectionFactory;

    @Autowired
    private PagedResourcesAssembler<AssignmentsOverviewProjection> resourceAssembler;

    @GetMapping("/assignments")   
    public PagedModel<EntityModel<AssignmentsOverviewProjection>> listAssignments(@RequestParam(required = false) String search,
                                                                                  @RequestParam(required = false) String sort,
                                                                                  Pageable pageable) {
        // Spring creates the Pageable object correctly for simple properties,
        // but for nested properties we need to fix it manually   
        pageable = fixPageableSort(pageable, sort, Set.of("client.firstName", "client.age"));

        Page<Assignment> assignments = assignmentRepository.filter(search, pageable);
        Page<AssignmentsOverviewProjection> projectedAssignments = assignments.map(assignment -> projectionFactory.createProjection(
                AssignmentsOverviewProjection.class,
                assignment));

        return resourceAssembler.toModel(projectedAssignments);
    }

    private Pageable fixPageableSort(Pageable pageable, String sortStr, Set<String> allowedProperties) {
        if (!pageable.getSort().equals(Sort.unsorted())) {
            return pageable;
        }

        Sort sort = parseSortString(sortStr, allowedProperties);
        if (sort == null) {
            return pageable;
        }

        return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
    }

    private Sort parseSortString(String sortStr, Set<String> allowedProperties) {
        if (StringUtils.isBlank(sortStr)) {
            return null;
        }

        String[] split = sortStr.split(",");
        if (split.length == 1) {
            if (!allowedProperties.contains(split[0])) {
                return null;
            }
            return Sort.by(split[0]);
        } else if (split.length == 2) {
            if (!allowedProperties.contains(split[0])) {
                return null;
            }
            return Sort.by(Sort.Direction.fromString(split[1]), split[0]);
        } else {
            return null;
        }
    }

}

字符串

mfuanj7w

mfuanj7w6#

Spring Data REST文档:
不支持按目录关联(即指向顶级资源的链接)排序。
https://docs.spring.io/spring-data/rest/docs/current/reference/html/#paging-and-sorting.sorting
我发现的一个替代方案是使用@ResResource(exported=false)。这是无效的(尤其是对于遗留的Spring Data REST项目),因为避免了资源/实体将被加载HTTP链接:

JacksonBinder
BeanDeserializerBuilder updateBuilder throws
 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of ' com...' no String-argument constructor/factory method to deserialize from String value

字符串
我尝试在annotations的帮助下激活sort by associations,但没有成功,因为我们总是需要覆盖JacksonMappingAwareSortTranslator.SortTranslator检测annotation的mappPropertyPath方法:

if (associations.isLinkableAssociation(persistentProperty)) {
                if(!persistentProperty.isAnnotationPresent(SortByLinkableAssociation.class)) {
                    return Collections.emptyList();
                }
            }

标注

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SortByLinkableAssociation {
}


在你的项目中,包括**@SortByLinkableAssociation**在搜索什么是排序的关联。

@ManyToOne(fetch = FetchType.EAGER)
@SortByLinkableAssociation
private Event event;


真的,我没有找到一个明确的和成功的解决方案,这个问题,但决定公开它,让考虑它,甚至Spring团队考虑包括在nexts版本。

相关问题