【发布时间】:2018-11-27 04:53:37
【问题描述】:
我正在尝试用 Spring Data 弄清楚具体的事情,那就是:如何通过一个 POST 请求创建一个实体和一个相关实体。
我可以通过单独的请求创建相关实体,但对于单个请求我不确定。 (不为其创建特定的控制器方法)。示例:
ReusableComponent.java
@Entity
public class ReusableComponent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy="component", cascade = CascadeType.ALL)
private List<Consumer> consumers = new ArrayList<>();
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Consumer> getConsumers() {
return consumers;
}
public void setConsumers(List<Consumer> consumers) {
this.consumers = consumers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Consumer.java
@Entity
public class Consumer<ResuableComponent> {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne(targetEntity=ReusableComponent.class)
private ResuableComponent component;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ResuableComponent getComponent() {
return component;
}
public void setComponent(ResuableComponent component) {
this.component = component;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ReusableComponentRepository.java
public interface ReusableComponentRepository extends CrudRepository<ReusableComponent, Long>
{
Iterable<ReusableComponent> findAll();
@RestResource(exported = false)
List<ReusableComponent> findByName(String name);
}
发布http://localhost:8080/reusableComponents
请求正文:
{ "name": "datagrid", "consumers": [{ "name": "financial app" }] }
GET http://localhost:8080/reusableComponents
回复:
{
"_embedded": {
"reusableComponents": [
{
"consumers": [],
"name": null,
"_links": {
"self": {
"href": "http://localhost:8080/reusableComponents/1"
},
"reusableComponent": {
"href": "http://localhost:8080/reusableComponents/1"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/reusableComponents"
},
"profile": {
"href": "http://localhost:8080/profile/reusableComponents"
}
}
}
如您所见,reusableComponent 实例中没有消费者。我以前有这个工作,但对于我的生活,我现在无法弄清楚。
【问题讨论】:
-
您在此处看到的是响应。检查您的数据库。它可能会被保存。我在上面的代码中没有看到任何错误
-
嗨 pvpkiran,我随后通过在 localhost:8080/reusableComponents/1 上调用 GET 请求检查了结果 - 但“consumers”属性只是一个空数组。
-
为您的消费者字段指定 FetchType
标签: java rest spring-boot jpa spring-data