I have two entities, a shelf and a book. A shelf may have several books (the relation is bidirectional). I exposed them as JpaRepositories.
Here's the problem:
- I create a shelf by sending {"name": "sci-fi"} to /shelves.(success)
- I create a book for this shelf by placing {"name": "mybook", "shelf": "localhost: 8080 / shelves / 1"} to / books. (Success)
- When I get the book I just created in / books / 1, it has the correct link to the parent shelf.
- But when I go to the shelves of / 1 / books, I get an empty result, {}!
Any ideas what I might be missing?
Now I have created a workaround, explicitly adding the book to my shelf in the beforeCreate event, but it seems like this should be completely unnecessary. (However, it fixes the problem.)
@HandleBeforeCreate(Book.class) public void handleCreate(Book book) {
Here are the entity classes:
@Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; @ManyToOne private Shelf shelf; public Shelf getShelf() { return shelf; } public void setShelf(Shelf shelf) { this.shelf = shelf; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Book other = (Book) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } @Entity public class Shelf { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; @OneToMany private List<Book> books = new ArrayList<Book>(); public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Shelf other = (Shelf) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
I am using Spring Boot 1.1.8.
spring-data-rest
gyoder
source share