3

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.

Community
  • 1
  • 1

1 Answers1

2

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.

rhorvath
  • 3,525
  • 2
  • 23
  • 30
  • This solution works for me, thank you! Is it possible to add several books to one category in one go? – Anatoly Antonov Aug 31 '16 at 05:46
  • I have tried reversing that put (or post) request without success yet. I've got no exception and my behaviour is matching the bug description you found. – rhorvath Aug 31 '16 at 13:24