Search code examples
springspring-bootone-to-manyspring-data-resthateoas

Delete resource in spring data rest hateoas with relationship


I have a category, item and roles for a restaurant. I can GET and POST request using postman but when I try to delete an entry in "category" it gives a 204 - no content but the data is still not being deleted. is this because the category has a many to one relationship with the restaurant. on the other hand, if I do a DELETE request for roles it works perfectly which doesn't have any direct relationship.

POJO for Categories

@Entity
@Table(name="Categories")
public class Category { 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    @ManyToOne
    @JoinColumn(name="restaurantId")
    private Restaurant restaurant;

    @OneToMany(mappedBy = "category", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Item> items;

    public Category () {
    }

    @Autowired
    public Category(String name, Restaurant restaurant, Set<Item> items) {      
        this.name = name;
        this.restaurant = restaurant;
        this.items = items;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Item> getItems() {
        return items;
    }
    public void setItems(Set<Item> items) {
        this.items = items;
    }
    public Restaurant getRestaurant() {
        return restaurant;
    }
    public void setRestaurant(Restaurant restaurant) {
        this.restaurant = restaurant;
    }
}

POJO for Roles

@Entity
@Table(name="Roles")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    @OneToMany(mappedBy = "role", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<User> users;

    public Role() {
    }   

    @Autowired
    public Role(String name, Set<User> users) {     
        this.name = name;
        this.users = users;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<User> getUser() {
        return users;
    }
    public void setUsers(Set<User> users) {
        this.users = users;
    }
}

Repository for Categories

public interface CategoryRepository extends CrudRepository<Category, Integer> {

}

Delete request in postman

DELETE localhost:9090/api/categories/7
Content-type: text/uri-list 
Response: 204 no content

Solution

  • I also have faced this issue. Please try adding the following parameter for OneToMany annotations

    orphanRemoval = true