【问题标题】:@RepositoryRestResource's collectionResourceRel attribute not being obeyed@RepositoryRestResource 的 collectionResourceRel 属性没有被遵守
【发布时间】:2017-06-26 08:43:57
【问题描述】:

我有一个 MongoRepository 的

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

工具可以是两种实现之一:

public class Screwdriver extends Tool
public class Hammer extends Tool

使用@JsonTypeInfo 映射工具

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

当我执行toolRepository.findAll() 时,这将返回一个 JSON 响应:

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

预期的反应应该是:

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

collectionResourceRel 对于包含 Json 映射数据的类没有被遵守。

进一步调查; PersistentEntitiesResourceMapping.getMetadataFor()(在 Spring 中)表示确保如果在 ResourceMetadata 缓存中没有这些工具子类的条目,则使用 TypeBasedCollectionResourceMapping,这会导致每个类在 json 响应中都有自己的条目。

有没有办法告诉 Spring data rest 一个特定的子类应该绑定到一个特定的存储库,在这种情况下有没有办法告诉 Spring data rest 螺丝刀是ToolRepository 的一部分,因此应该使用这个仓库的collectionResourceRel

【问题讨论】:

    标签: spring-data-mongodb spring-data-rest


    【解决方案1】:

    尝试设置这些注释:

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

    见工作example。这与 Mongo 无关,但我相信它会很有用...

    【讨论】:

    • 非常感谢 - @RestResource 似乎可以解决问题。必须将注释添加到我的所有子类中有点烦人(我有比上面更多的),但它解决了我的问题。再次感谢您
    • 忽略上述警告 - 将注释添加到假设的 Tool 类避免了我必须将其添加到所有子类的问题,因此完美的答案。
    • @alex.p 在我的代码中确认相同的行为。谢谢亚历克斯!我会更正我的答案...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2011-04-30
    • 2011-09-18
    • 1970-01-01
    • 2013-07-08
    • 2012-05-23
    • 1970-01-01
    相关资源
    最近更新 更多