Cześć.
Robie wypożyczalnie ksiązek, jestem na etapie metody odpowiedzialnej za samo wypożyczanie ksiązki. Wygląda ona tak:
Controller
@PostMapping("/book")
public void purchaseBook(@RequestParam("userID") int userID, @RequestParam("bookID") int bookID) {
rentalService.purchaseBook(userID,bookID);
}
Po wpisaniu ID ksiązki i ID użytkownika, jeżeli książka jest dostępna zostanie zapisana w bazie.
Relacje pomiędzy tabelami wymyśliłem tak:
Klasa Rentals, która skupia te dwie tabele wygląda tak:
package bookrental.model.book;
import bookrental.model.account.User;
import lombok.*;
import javax.persistence.*;
@Entity
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class Rentals {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToOne
private Book book;
@OneToOne
private User user;
}
Mam problem z utworzeniem obiektu typu Rentals w Serwisie. Musi on zawierać obiekt Book
oraz User
. Stworzyłem dla tych klas konstruktory tylko z bookID oraz userID. W metodzie prepareBookToRent
prosi mnie o podanie ID, przez co nie mogę utworzyć tego obiektu. Czy nie miał on byc generowany automatycznie? Jak mam to obejść?
package bookrental.service.book;
import bookrental.model.account.User;
import bookrental.model.book.Book;
import bookrental.model.book.BookRentals;
import bookrental.repository.book.BookRepository;
import bookrental.repository.book.BookRentalsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookRentalService {
private final BookRepository bookRepository;
private final BookRentalsRepository bookRentalsRepository;
@Autowired
public BookRentalService(BookRepository bookRepository, BookRentalsRepository bookRentalsRepository) {
this.bookRepository = bookRepository;
this.bookRentalsRepository = bookRentalsRepository;
}
public void rentBook(int userID, int bookID) {
if (bookRepository.doesBookExistsWithGivenID(bookID)) {
Book bookToRent = bookRepository.findOne(bookID);
if (bookToRent.isAvailable()) {
updateBookAvailabilityAndSaveToDb(bookToRent);
BookRentals preparedBookToRent = prepareBookToRent(userID, bookID);
bookRentalsRepository.save(preparedBookToRent);
} else {
throw new IllegalArgumentException("Book is no available");
}
}
throw new IllegalArgumentException("Book does not exist!");
}
private BookRentals prepareBookToRent(int userID, int bookID) {
return new BookRentals(new Book(bookID),new User(userID));
}
private void updateBookAvailabilityAndSaveToDb(Book bookToRent) {
bookToRent.setAvailable(false);
bookRepository.save(bookToRent);
}
}