【问题标题】:Spring data rest add element to collection [duplicate]Spring数据休息将元素添加到集合[重复]
【发布时间】:2023-03-16 13:55:01
【问题描述】:

我正在尝试在 Spring Data Rest 上的 tutorial 之后将元素添加到 @OneToMany 关系,我正在使用以下请求将帐户添加到用户帐户集合。

curl -v -X PUT -H "Content-Type: text/uri-list" -d "http://localhost:8080/account/1" http://localhost:8080/user/1/accounts

请求以 204 响应,当我检查用户帐户列表时没有任何变化。调试应用程序我可以看到实体正在保存,所以可能没有发生事务提交。我还注意到,如果我将关系更改为 @OneToOne,请求会按预期工作。

用户类

@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString(exclude = "accounts")
@EqualsAndHashCode(of = "id", callSuper = false)
@SequenceGenerator(name = "user_sq", sequenceName = "user_sq")
public final class User extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "user_sq")
    private Long id;

    //other properties

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner", orphanRemoval = true)
    private List<Account> accounts;

//    @OneToOne(cascade = CascadeType.ALL)
//    private Account accounts;
}

帐户类

@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = "id", callSuper = false)
@SequenceGenerator(name = "account_sq", sequenceName = "account_sq")
public final class Account extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "account_sq")
    private Long id;

    //other properties

    @ManyToOne
    private User owner;    
}

存储库

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

@RepositoryRestResource(collectionResourceRel = "users", path = "user")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {}

【问题讨论】:

  • 可能是龙目岛问题。尝试手动设置器和获取器
  • 这可能是由于关系是双向的。如果您在代码中执行此操作,则需要设置关系的双方以使关系正确级联。您可以尝试删除从 Account 到 Owner 的反向引用,看看这是否会影响结果?如果这证实了原因,请在此处查看解释和可能的解决方法:stackoverflow.com/questions/30464782/…
  • 谢谢@AlanHay!另一个帖子做到了,解决方案有点奇怪,也许我将来可以找到更好的解决方案(如果有的话)。在这种情况下,删除双向是一种选择,但在未来的另一个场景中可能不会,并且使用 @PreUpdate/@PrePersist 感觉不对,我认为我不需要使用它(两种解决方案都有效)

标签: spring spring-data spring-data-rest


【解决方案1】:

尝试在您的 POST 或 PUT/PATCH 请求中使用类似此正文的内容:

{
    // user properties...
    "accounts": [
            "http://localhost:8080/accounts/1",
            "http://localhost:8080/accounts/2"
        ]
}

要创建新用户(使用他的帐户),请使用 POST 请求到 http://localhost:8080/users

要更新当前用户(及其帐户),请使用 PUT/PATCH 请求到 http://localhost:8080/users/1(1 - 是当前用户的 ID)

【讨论】:

  • 感谢您的回答,我知道您的建议有效,但这不在我的问题范围内。我正在尝试理解/使用您在问题中链接的文档中可以找到的内容
  • 这对我来说不再适用于 Spring Boot 1.5.2 和 Spring Data REST 2.6.1 和多态性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
相关资源
最近更新 更多