I'm trying to build a REST API with Spring boot application for web and mobile app. In my application I have multiple foreign keys, and I want to pass only the id of the object instead of the entire object. See example below.
Model Book
// imports
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String isbn;
@ManyToOne
@JoinColumn(name = "category_id", updatable = false)
private BookCategory bookCategory;
public Book() {
}
public Book(Integer id, String title, String isbn, BookCategory bookCategory) {
this.id = id;
this.title = title;
this.isbn = isbn;
this.bookCategory = bookCategory;
}
// getters and setters
}
Model Category
// imports
@Entity
public class BookCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany(mappedBy = "bookCategory", cascade = CascadeType.ALL)
private List<Book> books;
public BookCategory() {
}
public BookCategory(Integer id, String name) {
this.id = id;
this.name = name;
}
// getters and setters
}
Book Controller
// imports
@RestController
@RequestMapping(path = "/api/v1")
public class BookController {
@Autowired
private BookRepository bookRepository;
// other methods for index, show, put and delete
@PostMapping(path = "/books")
public book createBook(@RequestBody Book book) {
return bookRepository.save(book);
}
}
Book Repository
// imports
public interface BookRepository extends PagingAndSortingRepository<Book, Integer> {
}
Book categories are pre-loaded on database, and I don't want to allow the client to change them or to add new ones.
Here's the JSON POST I tried and the object that was stored on database.
Request
{
"title": "Tirant lo blanc",
"isbn": "9788475841199",
"category_id": 4
}
Response
{
"title": "Tirant lo blanc",
"isbn": "9788475841199",
"bookCategory": null
}
I tried to send it as object too, but the result is null.
{
"title": "Tirant lo blanc",
"isbn": "9788475841199",
"category_id": {
"id": 4
}
}
How can I send the category id to correctly store the book on database? Is better to send the entire category object instead? I tried too, but the response and the stored book on database is always on category null.