Modify @OneToMany entity in Spring Data Rest without its repository

后端 未结 1 1425
走了就别回头了
走了就别回头了 2020-12-25 08:13

In my project I use object of type A which has OneToMany relation (orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.EAGER) to objects of type

相关标签:
1条回答
  • 2020-12-25 08:55

    I managed to change the child entity as follows. As a sample I used the following entities:

    @Entity
    @Data
    @NoArgsConstructor
    public class One {
    
        @Id
        @GeneratedValue
        private Long id;
    
        private String name;
    
        @OneToMany(cascade = ALL)
        private List<Many> manies = new ArrayList<>();
    
    }
    
    @Entity
    @Data
    @NoArgsConstructor
    public class Many {
    
        public Many(String name) {
            this.name = name;
        }
    
        @Id
        @GeneratedValue
        private Long id;
    
        private String name;
    }
    

    I just have a repository for One exposed.

    (My examples use the excellent httpie - CLI HTTP client)

    Removing an item using json patch

    This example will remove the second item in the manies list. You could use @OrderColumn to make sure that you can rely on the order of list items.

    echo '[{"op":"remove", "path":"/manies/1"}]' | http PATCH :8080/ones/1 Content-Type:application/json-patch+json -v
    
    PATCH /ones/1 HTTP/1.1
    Content-Type: application/json-patch+json
    
    [
        {
            "op": "remove", 
            "path": "/manies/1"
        }
    ]
    

    Replacing the entire list using json patch

    This sample replaces the list with the array specified in the value.

    echo '[{"op":"add", "path":"/manies", "value":[{"name":"3"}]}]' | http PATCH :8080/ones/1 Content-Type:application/json-patch+json -v
    
    PATCH /ones/1 HTTP/1.1
    Accept: application/json
    Content-Type: application/json-patch+json
    
    [
        {
            "op": "add", 
            "path": "/manies", 
            "value": [
                {
                    "name": "3"
                }
            ]
        }
    ]
    

    Adding an item to the list using json patch

    This sample adds an item to the end of a list. Also here the client just needs to know the length of the list before the update. So the order does not really matter here.

    echo '[{"op":"add", "path":"/manies/-", "value":{"name":"4"}}]' | http PATCH :8080/ones/1 Content-Type:application/json-patch+json -v
    
    PATCH /ones/1 HTTP/1.1
    Accept: application/json
    Content-Type: application/json-patch+json
    
    [
        {
            "op": "add", 
            "path": "/manies/-", 
            "value": {
                "name": "4"
            }
        }
    ]
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题