【问题标题】:Saving nested entities in Spring Data Rest在 Spring Data Rest 中保存嵌套实体
【发布时间】:2015-07-09 18:43:46
【问题描述】:

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

帐户

@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 ...
}

帐户标识符

@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"])

有什么方法可以同时使用"id":null 存储帐户和嵌套帐户标识符? 我想避免对不同的端点做两个POSTs。使用 @JsonManagedReference@JsonBackReference 还有其他不利的缺点。

当我在 Java 代码中使用实体对象时,它可以完美运行。

【问题讨论】:

    标签: spring-data-rest


    【解决方案1】:

    我认为你别无选择,必须做各种 POST。我为此付出了很多努力,玩弄了双向和单向关联,才得出这个结论。

    您可以做的最简单的操作是在/account 上使用空的identifiers 进行POST,然后在/accountidentifiers 上使用account 字段等于您的第一个@987654327 答案中的location 字段@,您无需再次PATCH 帐户实体即可更新关系。

    【讨论】:

    • 感谢您的见解。它会这样工作。我最终删除了标识符存储库并通过帐户存储库使用标识符。这是一个更大的开销,但我可以避免第二个POST
    猜你喜欢
    • 2018-05-28
    • 2019-09-30
    • 2018-03-10
    • 2014-05-05
    • 2014-08-25
    • 2020-04-22
    • 1970-01-01
    • 2015-03-14
    相关资源
    最近更新 更多