I have a case, when from request I get a BookDTO with author id, and I have to create and save new book to database with nested Author entity. Now I get author object from database before creating book, but I am not sure that this is a right way. What if I with have multiple nested entity inside one. I have to get them all from DB before save it, or there is a more clean and fast way to do it?
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import javax.persistence.*;
@Entity
@Getter
@Setter
class Book
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "author_id")
private Author author;
public Book(BookDTO bookDTO, Author author)
{
this.setName(bookDTO.getName());
this.setAuthor(author);
}
}
@Getter
@Setter
class BookDTO
{
private String name;
private Long author_id;
}
@Entity
class Author
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
@Repository
interface BookRepo extends JpaRepository<Book, Long>
{
}
@Repository
interface AuthorRepo extends JpaRepository<Author, Long>
{
}
@Controller
class BookController
{
@Autowired
AuthorRepo authorRepo;
@Autowired
BookRepo bookRepo;
@MutationMapping
public Book createUser(BookDTO bookDTO)
{
// Getting author from DB before create book
Author author = authorRepo.getReferenceById(bookDTO.getAuthor_id());
Book book = new Book(bookDTO, author);
return bookRepo.save(book);
}
}
How can I save author ID for book without getting Author from database?