Spring JPA REST 按嵌套属性排序

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

我有实体

Market
Event
Market
实体有一列:

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

接下来我有一个存储库:

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
,但没有成功。我应该怎么做才能让它发挥作用?

java spring rest spring-data-jpa spring-data-rest
6个回答
8
投票

基于 Spring Data JPA 文档 属性表达式

...您可以在方法名称中使用 _ 来手动定义遍历点...

您可以在 REST 查询中添加下划线,如下所示:

/api/markets?projection=expanded&sort=event_name,asc


3
投票

只需降级

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评论这个问题

在 Hopper 版本中,按嵌套属性排序对我来说效果很好,但我确实在 Ingalls 版本的 RC 版本中遇到了以下错误。Ingalls 版本的 RC 版本中的错误。据报道,此问题已修复,

顺便说一句,我尝试了

v3.0.0.M3
,报告已修复但无法与我合作。


1
投票

我们遇到过这样的情况:我们想要按链接实体中的字段进行排序(这是一对一的关系)。最初,我们使用基于 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);
}
}

使用的Spring boot版本:2.3.8.RELEASE

我们还有实体存储库并使用投影:

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

0
投票

您的

MarketRepository
可以有一个
named query
,例如:

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

您可以使用

name
 从 url 获取您的 
@RequestParam

参数

0
投票

这个页面有一个可行的想法。这个想法是在存储库顶部使用控制器,并单独应用投影。

这是一段有效的代码(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;
        }
    }

}

0
投票

来自 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 的帮助下通过可链接关联激活排序,但没有成功,因为我们总是需要重写

mappPropertyPath
JacksonMappingAwareSortTranslator.SortTranslator
方法来检测注释:

            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 团队考虑将其包含在下一个版本中。

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