我正在尝试用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" }] }
获取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实例中没有使用者。我之前有过这个工作,但对于我的生活,我现在无法理解。
答案 0 :(得分:0)
我通过删除ReusableComponent实体的consumers属性上的@OneToMany装饰器中的mappedBy="component"
属性来实现它,如下所示:
@OneToMany(cascade = CascadeType.ALL)
private List<Consumer> consumers = new ArrayList<>();
以上作品完美无缺。