@RepositoryRestResource's collectionResourceRel attribute not being obeyed

血红的双手。 提交于 2019-12-25 08:59:53

问题


I have a MongoRepository of

@RepositoryRestResource(collectionResourceRel = "tools")
public interface ToolRepository extends MongoRepository<Tool, Long>

Tool can be one of 2 implementations:

public class Screwdriver extends Tool
public class Hammer extends Tool

Tool is mapped using @JsonTypeInfo

@JsonTypeInfo(use = 
com.fasterxml.jackson.annotation.JsonTypeInfo.Id.CLASS, include = 
As.PROPERTY, property = "_class")
public abstract class Tool

When I do toolRepository.findAll() this returns a JSON response of :

{
  "_embedded" : {
    "screwdrivers" : [ {
      "name" : "Screwdriver",
      ...
    } ],
    "hammers" : [ {
      "name" : "Hammer",
      ...
      }
 }

Expected response should be :

{
  "_embedded" : {
    "tools" : [ {
      "name" : "Screwdriver",
      ...
      },
      {
      "name" : "Hammer",
      ...
      }
 }

The collectionResourceRel is not being obeyed for classes with Json mapping data in.

Investigating further; PersistentEntitiesResourceMapping.getMetadataFor() (within Spring) is saying make sure that if there's no entry for these subclasses of tool inside the ResourceMetadata cache then use a TypeBasedCollectionResourceMapping which results in each class having its own entry in the json response.

Is there a way of telling Spring data rest that a specific subclass should be bound to a specific repository, in this case is there a way of telling Spring data rest that Screwdriver is part of the ToolRepository and therefore should use the collectionResourceRel of this repository?


回答1:


Try to set these annotations:

@RestResource(rel = "tools", path = "tools")
public abstract class Tool {...}

@RepositoryRestResource(path = "tools", collectionResourceRel = "tools", itemResourceRel = "tool")
public interface ToolRepository extends MongoRepository<Tool, Long> {...}

See working example. It's not about Mongo but I'm sure it will be useful...



来源:https://stackoverflow.com/questions/44755908/repositoryrestresources-collectionresourcerel-attribute-not-being-obeyed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!