简体   繁体   English

Spring JPA - 在多对一关系中发布资源

[英]Spring JPA - post resource in many to one relationships

This question is closely related to this one (Solving this one here, will probably also solve the other).这个问题是密切相关的这一个(在这里解决这一块,可能还解决了其他)。

In my spring mvc app (github) I have two resources: Cart and Item where a cart can have multiple items.在我的spring mvc 应用程序(github)中,我有两个资源: CartItem ,其中一个购物车可以有多个项目。

The CartController maps a POST method which adds a random item to a cart with a given ID CartController映射一个 POST 方法,该方法将随机项目添加到具有给定 ID 的购物车

/* Forgetting about response entity and null checking etc. for now */

    @PostMapping("carts/rdm/{id}")
    public Cart addRandomItem(@PathVariable("id") long id)
    {
        String[] rdmItemNames = {"toothbrush", "shampoo", "body wash"};
        int rnd = new Random().nextInt(rdmItemNames.length);
        String itemName = rdmItemNames[rnd];

        // Add new item to the cart with given id
        Cart cart = dao.getById(id);

        Item item = new Item();
        item.setItemName(itemName);

        // This works but I have to create a new cart object with same id
        Cart sameCart = new Cart();
        sameCart.setId(cart.getId());
        item.setCart(sameCart);

        // This doesn't work, no surprise but I would like to
        // just retrieve the Cart, add the new Item and be done.
        // item.setCart(cart);
        // cart.getItems().add(item);
        return dao.save(cart);
    }

After POSTing to http://localhost:9100/carts/rdm/1 , I get the following Cart json发布到http://localhost:9100/carts/rdm/1 ,我得到以下Cart json

{
    "id": 1,
    "items": [
        {
            "id": 0,
            "itemName": "body wash",
            "cart": {
                "id": 1,
                "items": null
            }
        }
    ]
}

Feels like I am not understanding JPA correctly.感觉我没有正确理解JPA。 This boils down again to why the Item object needs to contain the whole Cart object.这再次归结为为什么Item对象需要包含整个Cart对象。 If Item only contained the foreign key (the cart id), then I could produce a json like this如果Item只包含外键(购物车 ID),那么我可以生成这样的 json

   {
        "id": 1,
        "items": [
            {
                "id": 0,
                "itemName": "body wash",
                "cart_id": 1
            }
        ]
    }

JPA is a high level ORM Framework. JPA 是一个高级 ORM 框架。 Which means that the object-references of java are converted to relational references in your Database.这意味着 java 的对象引用被转换为数据库中的关系引用。

So in your database you will have a foreign key where an item references a car.因此,在您的数据库中,您将有一个外键,其中项目引用了汽车。

JPA converts these relational-relation to object-relations, which means that you will get not only the reference of the car but the car object. JPA 将这些关系关系转换为对象关系,这意味着您不仅会获得汽车的引用,还会获得汽车对象。

Your Rest-API return the Java-Object which holds Object-References.您的 Rest-API 返回包含对象引用的 Java 对象。 That is why your item contains a Car-Object.这就是为什么您的项目包含汽车对象。

If you want to return only the car_id you have to map your output to a new object.如果只想返回 car_id,则必须将输出映射到新对象。

I am junior with REST , but my advice would be : Create CartServices class .我是 REST 的初中生,但我的建议是:创建 CartServices 类。 Controller only to transfer data to Services.控制器仅将数据传输到服务。 Use @transactional annotations.使用@transactional 注释。 It is hard to read .很难读。 I wrote very similar Application : IF you want to check : https://github.com/justassub/ShopProject/tree/master/RESTserver/src/main/java/lt/it/akademija Sorry , it was my first application and not everything was in english.我写了非常相似的应用程序:如果你想检查: https : //github.com/justassub/ShopProject/tree/master/RESTserver/src/main/java/lt/it/akademija对不起,这是我的第一个应用程序而不是一切都是英文的。 BUT IT IS VERY SIMILAR - only Cart - users.但它非常相似 - 只有购物车 - 用户。

When you wrote :当你写道:

@OneToMany(mappedBy = "cart")
private Set<Item> items;

write method :写法:

public void addItem(Item item) {
    this.items.add(item);
    item.setCart(this);
}

and then Cart.addItem(item);然后 Cart.addItem(item); And other OF course you need to create getCart/setCart in your items List和其他当然你需要在你的项目列表中创建 getCart/setCart

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM