Search code examples
spring-data-mongodbspring-data-rest

@RepositoryRestResource's collectionResourceRel attribute not being obeyed


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?


Solution

  • 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...