How to reference an entity with inheritance in Spring Data REST when POSTing new entity?

前端 未结 3 1571
我寻月下人不归
我寻月下人不归 2021-01-13 08:07

I have entities with joined inheritance:

Supporter

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@Js         


        
相关标签:
3条回答
  • 2021-01-13 08:32

    You should be able to workaround this by setting @JsonTypeInfo(use= JsonTypeInfo.Id.NONE) at the property/method level e.g.

    Try with this:

    @ManyToOne // same error with @OneToOne
    @JoinColumn(name = "supporter_id", referencedColumnName = "id", nullable = false)
    @JsonTypeInfo(use= JsonTypeInfo.Id.NONE)
    public SupporterEntity getSupporter() {
        return supporter;
    }
    
    0 讨论(0)
  • 2021-01-13 08:36

    It looks like a Jackson problem. To be specific, it's the following code in com.fasterxml.jackson.databind.deser.SettableBeanProperty:

    if (_valueTypeDeserializer != null) {
       return _valueDeserializer.deserializeWithType(jp, ctxt, _valueTypeDeserializer);
    }
    return _valueDeserializer.deserialize(jp, ctxt);
    

    Without inheritance _valueDeserializer.deserialize would be called which in turn runs some Spring code to convert the URI to a Supporter.

    With inheritance _valueDeserializer.deserializeWithType is called and vanilla Jackson, of course, expects an object, not a URI.

    If supporter was nullable you could first POST to /contacts and then PUT the supporter's URI to /contacts/xx/supporter. Unfortunately I am not aware of any other solution.

    0 讨论(0)
  • 2021-01-13 08:41

    Just another workaround using a RelProvider:

    1. Do not use @JsonTypeInfo
    2. Create a RelProvider for SupporterEntity sub-classes

      @Component
      @Order(Ordered.HIGHEST_PRECEDENCE)
      public class SupporterEntityRelProvider implements RelProvider {
      
        @Override
        public String getCollectionResourceRelFor(final Class<?> type) {
          return "supporters";
        }
      
        @Override
        public String getItemResourceRelFor(final Class<?> type) {
          return "supporter";
        }
      
        @Override
        public boolean supports(final Class<?> delimiter) {
          return org.apache.commons.lang3.ClassUtils.isAssignable(delimiter, SupporterEntity.class);
        }
      }
      

    See also:

    • https://jira.spring.io/browse/DATAREST-344
    • http://docs.spring.io/spring-hateoas/docs/current/reference/html/#configuration.at-enable
    0 讨论(0)
提交回复
热议问题