Spring Data Rest post 无法保存嵌套对象

Spring Data Rest post fails to save nested object

我有这些对象:

@Data
@Entity
@Table
@EqualsAndHashCode(callSuper = true)
public class User extends AbstractEntity implements Serializable {

   private static final long serialVersionUID = -55089179131569489L;

   private String username;
   private String email;
   private boolean admin;
   private String name;
   private String surname;

   @OneToMany(mappedBy = "owner")
   private List<Ad> ads;
}

@Entity
@Table
@Data
@EqualsAndHashCode(callSuper = true)
public class Ad extends AbstractEntity implements Serializable {

    private static final long serialVersionUID = -4590938091334150254L;
    private String name;
    private String description;
    private double price;

    @Enumerated(EnumType.STRING)
    private Category category;

    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "OWNER_ID")
    private User owner;

}

当我尝试使用 Ad.class 类型的对象执行 POST 并且在 User.class 类型的现有对象(已经在数据库中)中时,服务仅保存广告对象和连接列 "OWNER_ID" 保持为空。

我认为映射是正确的。你能帮我找出问题吗?

这是我的存储库:

@Repository
@Transactional(readOnly = true)
public interface AdRepository extends PagingAndSortingRepository<Ad, String> 
{}  

这是我的 RestRepository

@RepositoryRestResource(collectionResourceRel = "ad", path = "ad")
public interface AdRestRepository extends PagingAndSortingRepository<Ad, String> {}

如果我退一步概括一下你的问题,

您正在尝试 POST 一个 子资源 并期待

的两个操作
  • 制作新资源(广告)
  • 与所有者(用户)建立联系

一次调用即可实现。

但不幸的是 spring-data-rest 支持这种行为。您需要调用 2 次才能执行此操作。

  • 制作资源 (Ad) => POST/ads 实际负载
  • 第二次建立关联=> POST to users/{ownerId} with the hateoas link 第一次调用创建的资源。

查看官方文档的 this 部分。