我有这些对象:
@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 的现有对象(已在数据库中)中执行时,服务仅保存 Ad 对象并且连接列“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
并带有实际负载 - 第二次使用第一次调用创建的资源的 hateoas 链接 关联 => POST 到
users/{ownerId}
.
看看this官方文档部分。
关于java - Spring Data Rest 发布无法保存嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52434052/