无法为类X创建自链接.找不到持久实体



使用Spring Data REST时,标题中出现错误。如何解决?

Party.java:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, property="@class")
@JsonSubTypes({ @JsonSubTypes.Type(value=Individual.class, name="Individual") })
public abstract class Party {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  protected Long id;
  protected String name;
  @Override 
  public String toString() {
    return id + " " + name;
  }
  ...getters, setters...
}

Individual.java:

@Entity
public class Individual extends Party {
  private String gender;
  @Override
  public String toString() {
    return gender + " " + super.toString();
  }
  ...getters, setters...
}

PartyRepository.java:

public interface PartyRepository extends JpaRepository<Party,Long> {
}

如果我POST,它会正确地保存到数据库:

POST /parties {"@class":"com.example.Individual", "name":"Neil", "gender":"MALE"}

但返回一个400错误:

{"cause":null,"message":"Cannot create self link for class com.example.Individual! No persistent entity found!"}

从存储库检索后,它看起来像是一个个体:

System.out.println(partyRepository.findOne(1L)); 
//output is MALE 1 Neil

看起来杰克逊能发现这是一个人:

System.out.println( new ObjectMapper().writeValueAsString( partyRepository.findOne(1L) ) );
//output is {"@class":"com.example.Individual", "id":1, "name":"Neil", "gender":"MALE"}

SDR为什么搞不清楚?

如何修复?最好使用XML配置。

版本:
SDR 2.2.0.发布
SD JPA 1.7.0.发布
休眠4.3.6.最终

SDR存储库需要一个非抽象实体,在您的情况下,它应该是Individual。你可以在这里搜索或搜索SDR为什么期望一个非抽象实体的解释。

我自己试过你们的代码,SDR甚至不能用于POST,我看到下面的错误消息。

{
    "cause": {
        "cause": null,
        "message": "Can not construct instance of com.spring.data.rest.test.Party, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type informationn at [Source: org.apache.catalina.connector.CoyoteInputStream@30217e25; line: 1, column: 1]"
    },
    "message": "Could not read JSON: Can not construct instance of com.spring.data.rest.test.Party, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type informationn at [Source: org.apache.catalina.connector.CoyoteInputStream@30217e25; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.spring.data.rest.test.Party, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type informationn at [Source: org.apache.catalina.connector.CoyoteInputStream@30217e25; line: 1, column: 1]"
}

我建议您将respository从PartyRepository更改为IndividualRepository

public interface IndividualRepository extends JpaRepository<Individual,Long> {
}

您看到了这个错误,因为SDR在构建链接时找不到引用Individual的存储库。只需添加个人简历而不导出即可解决您的问题。

@RepositoryRestResource(exported = false)
public interface IndividualRepository extends JpaRepository<Individual,Long> {
}

最新更新