【发布时间】: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