在Spring Data Rest中保存嵌套实体

时间:2015-07-09 18:43:46

标签: spring-data-rest

我无法通过REST使用Spring Data Rest保存我的实体。 正如你在下面看到的,我有一个循环依赖,我试图用杰克逊解决。这是解释问题的一个小例子。

帐户

@Entity
@JsonIdentityInfo(property = "id", generator = ObjectIdGenerators.PropertyGenerator.class)
public class Account implements Serializable
{
    @Id <...>
    private Long id;

    private String uid;

    @OneToMany <...>
    //@JsonIdentityReference
    private List<AccountIdentifier> identifiers;

    // Getters, Setters ...
}

AccountIdentifier

@Entity
@JsonIdentityInfo(property = "id", generator = ObjectIdGenerators.PropertyGenerator.class)
public class AccountIdentifier implements Serializable
{
    @Id <...>
    private Long id;

    private String value;

    @ManyToOne <...>
    //@JsonIdentityReference(alwaysAsId = true)
    private Account account;

    // Getters, Setters ...
}

AccountRepository

@RepositoryRestResource(collectionResourceRel = "accounts", path = "accounts")
public interface AccountRepository extends PagingAndSortingRepository<Account, Long>

AccountIdentifierRepository

@RepositoryRestResource(collectionResourceRel = "accountidentifiers", path = "accountidentifiers")
public interface AccountRepository extends PagingAndSortingRepository<AccountIdentifier, Long>

通过此设置,我可以完美地读取存储在我的数据库中的值。

当我想通过POST将值保存到/accounts端点时,问题就开始了。我想保存以下JSON:

 '{"id":null, "uid":"test-uid", "identifiers":[{"id":null,"value":"test-value"}]}'

这会引发JsonMappingException

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: demo.domains.AccountIdentifier["account"]->demo.domains.Account["identifiers"]->java.util.ArrayList[0]->demo.domains.AccountIdentifier["account"]-[...]

当我使用@JsonIdentityReference注释两个实体时,我在循环引用上得到NullPointerExceptions

com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: demo.domains.Account["identifiers"]->java.util.ArrayList[0]->demo.domains.AccountIdentifier["account"])

有没有办法将帐户和嵌套的AccountIdentifier与"id":null一起存储? 我想避免对不同的端点做两个POST。使用@JsonManagedReference@JsonBackReference还有其他不良后果。

当我在Java代码中使用实体对象时,它非常有效。

1 个答案:

答案 0 :(得分:0)

我认为你别无选择,必须做各种POST。我一直在努力解决这个问题,玩双向和单向联想,得出这个结论。

最简单的方法是POST /accountidentifiers/accountidentifiers account location字段等于{POST在您的第一个PATCH的答案中填写1}}字段,您不需要再次<dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> </dependentAssembly> TO <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.1" /> </dependentAssembly> 您的帐户实体来更新关系。

相关问题