我是SpringDataREST的新手,在成功创建了一些实体之后,我遇到了一个问题。我有一个表shopping\u list,它包含一些shopping\u list\u产品,shopping\u list\u产品与shopping\u list有关系,所有这些都在mysql数据库中。问题是,当我尝试创建一个包含一些产品的购物列表时,会创建列表,但不会创建产品。在响应中,我可以看到id为“null”的产品。
这些是类(避免getter/setter):
购物清单:
@Entity
@Table(name = "shopping_list")
public class ShoppingList {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Date creationDate;
@RestResource(exported=false)
@OneToMany(mappedBy="shoppingList")
private List<ShoppingListProduct> shoppingListProducts;
购物清单产品:
@Entity
@Table(name = "shopping_list_products")
public class ShoppingListProduct {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private boolean checked;
@ManyToOne(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "shopping_list_id")
private ShoppingList shoppingList;
当我试着用 Postman 插入一些产品时会发生这样的情况:
我插入以下内容:
{
"name" : "name",
"creationDate" : "2018-12-12",
"shoppingListProducts" : [
{
"name" : "product 1",
"checked" : false
},
{
"name" : "product 2",
"checked" : true
}
]
}
我得到一个201(已创建)响应,结果如下:
{
"name": "name",
"creationDate": "2018-12-12",
"shoppingListProducts": [
{
"name": "product 1",
"checked": false,
"resourceId": null
},
{
"name": "product 2",
"checked": true,
"resourceId": null
}
],
"resourceId": 60,
"_links": {
"self": {
"href": "http://localhost:8080/shoppingLists/60"
},
"shoppingList": {
"href": "http://localhost:8080/shoppingLists/60"
}
}
}
如您所见,为shoppinglist中的产品创建的resourceid为null,如果我转到数据库,则不会创建任何产品。
我找不到有什么问题,所以我非常感谢你的帮助。
谢谢!
2条答案
按热度按时间qf9go6mv1#
请尝试将id的注解更改为:
jexiocij2#
好吧,多亏了@billyfrost,我在@onetomany上添加了一个cascade,之后我收到一个500错误,说shopping\u list\u id不能为空。因此,我编辑了shoppinglistproducts的setter来设置当前的购物列表,如下所示:
现在成功了!
非常感谢你的帮助!