Reputation: 71
I'm trying to build simple application with Spring Boot + Data Rest + JPA.
A have Category and Book entities with one to many relationship:
<!-- language-all: java -->
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Set<Book> books;
...getters & setters next...
}
and
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToOne
private Category category;
...getters & setters next...
}
Simple repositories for each entity
@RepositoryRestResource
public interface BookRepository extends JpaRepository<Book, Long> {}
@RepositoryRestResource
public interface CategoryRepository extends JpaRepository<Category, Long> {}
And application:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Application starts successfully and I can create books and categories.
Q.: How I can create and remove a references between them?
I tried solution described here: POSTing a @OneToMany sub-resource association in Spring Data REST - didn't work for me: on PUT request with "ContentType: text/uri-list" header I have response code 204 and no changes in the database. Looking deeper I was found the following debug message in the log:
s.w.s.m.m.a.RequestMappingHandlerMapping :
Did not find handler method for [/categories/1/books]
This url is available only for GET requests.
Q.: Any ideas what is wrong in my configuration?
Thanks.
Upvotes: 3
Views: 3444
Reputation: 3725
To create a relation between book(id:1) and category(id:1):
curl example:
curl -X PUT -H "Content-Type: text/uri-list" -d "http://localhost:8080/categories/1" http://localhost:8080/books/1/category
To remove this relation just do a delete request to the same address
curl example:
curl -X DELETE http://localhost:8080/books/1/category
And to answer your 2nd question as well: your configuration looks good and I have tested this example on your code.
Upvotes: 2