@ManyToOne关系在Spring Data REST中插入空对象

问题描述 投票:0回答:2

我是Spring Data REST的新手,在成功创建了一些实体后,我遇到了一个问题。我有一个table shopping_list,其中包含一些shopping_list_products,shopping_list_product与shopping_list有关系,所有这些都在mysql数据库中。问题是,当我尝试创建一个包含某些产品的购物清单时,会创建列表但不会创建产品。在响应中,我可以看到id为“null”的产品。

这些是类(避免getter / setters):

购物清单:

@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;

ShoppingListProduct:

@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;

当我尝试用邮递员插入一些产品时会发生这种情况:

我插入这个:

{
"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,如果我转到数据库,则不会创建任何产品。

我找不到有什么问题,所以我非常感谢你的帮助。

谢谢!

java mysql spring jpa
2个回答
0
投票

请尝试将id的注释更改为:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

0
投票

好吧,多亏了@BillyFrost,我在@OneToMany上添加了一个级联,之后我收到500错误,说shopping_list_id不能为空。所以,我编辑了设置当前购物清单的shoppingListProducts的setter,如下所示:

public void setShoppingListProducts(List<ShoppingListProduct> shoppingListProducts) {

    for (ShoppingListProduct sp : shoppingListProducts) {
            sp.setShoppingList(this);   
    }

        this.shoppingListProducts = shoppingListProducts;
}

现在它奏效了!

非常感谢你的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.