我有 2 个具有双向关联的 jpa 实体。
实体 Container
持有项目集合(oneToMany)
省略 getter/setter
@javax.persistence.Entity
@Table(name = "CONTAINER")
public class Container implements Serializable {
private static final long serialVersionUID = -3288335692695653843L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "container", cascade = CascadeType.ALL)
private List<Item> items;
}
实体 Item
包含对容器 (ManyToOne) 的引用,具有属性值和日期。
省略 setter/getter
@javax.persistence.Entity
@Table(name = "ITEM")
public class Item implements Serializable {
private static final long serialVersionUID = -758343957629274274L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Basic
private Long value;
@Basic
private Date date;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "CONTAINER_ID")
private Container container;
}
我还使用 spring-data 存储库来公开数据。
我的接口(interface)存储库只是扩展了 CrudRepository<Container, Long>
和 CrudRepository<Item, Long>
@RepositoryRestResource
public interface ItemRepository extends CrudRepository<Item, Long> {
}
@RepositoryRestResource
public interface ContainerRepository extends CrudRepository<Container, Long> {
}
我正在尝试通过 REST 调用创建项目。
首先,我在项目存储库上尝试了这个 rest/items
POST { "value" : 666, "date" : "2016-01-31T23:00:00.000+0000", "container": {"id":"1"}}
但它只是在容器上创建具有空引用的项目。
当我尝试通过容器存储库添加时 rest/containers/1/items
POST { "value" : 666, "date" : "2016-01-31T23:00:00.000+0000", "container": {"id":"1"}}
我得到 HTTP/1.1 204 No Content
和 <Response body is empty>
.没有创建实例。
我的问题是如何通过引用容器的 REST 调用添加项目。
编辑:为了说明我的问题,我想为现有容器添加新项目。我不确定在通过 rest(json) 创建 Item 实例时如何处理外部 ID key
最佳答案
我通过使用 json 中容器的链接解决了这个问题。
POST { “值”:666,“日期”:“2016-01-31T23:00:00.000+0000”,“容器”:“http://localhost:8080/container/1”}
我不确定在没有 spring-data-rest
的情况下它是否工作
编辑:我应该指出,链接的资源必须是@RepositoryRestResource
并且应该是聚合根。
关于java - 通过 REST 调用使用外键将项目添加到集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902946/