skip to Main Content

I have created one project in spring boot which is book-store . I have one post service which is used to take details of book and author also and save that into db [both book and author at same time].

I want to create a logic where i can save new book for already existing author but i tried several ways and im unable to do.

I need a way to do this

enter image description here

Here what i tried doing is i passed author email in path variable and passing a new book object as a json . i created a service which used to fetch particular author from db and i set that author object to my book object but it is saving that author object again and it is creating duplicate entry for that

author table:
here you can see duplicate entry of same author happend which i dont want

enter image description here

book table:
book table is correct here new book got saved
enter image description here

github link

this is my github link you can take a code and please help me to solve this issue . thanks in advance

2

Answers


  1. Based on your Book and Author classes, it seems you have a one-to-one relationship between them. However, to allow an author to have multiple books, you’ll need a one-to-many relationship between Author and Book.

    author table: here you can see duplicate entry of same author happend
    which i dont want

    Its because of the one-to-one relationship. This happens because each time you save a new book, it attempts to save the associated author as a new entry.

    Login or Signup to reply.
  2. github project seems to be no relation with your postman demo.

    But in your source code, AuthorServiceImpl.java shows the limit for creating author.
    If author has existed, it will only create book; else it will be able to create author.

    if au

     @Override
    public Author saveAuthor(Author author) {
        Optional<Author> optionalAuthor = this.authorRepository.findById(author.getAuthorId());
        // saving new author
        if(!optionalAuthor.isPresent()){
            return this.authorRepository.save(author);
        }
        else{
            // if author is present just add new books if any
            Author dbAuthor = optionalAuthor.get();
            List<Book> dbBookList = dbAuthor.getBooks();
            List<Book> newBooks = author.getBooks();
    
            // fetching each new book
            for(Book book : newBooks){
                // for each new book setting author
                book.setAuthor(dbAuthor);
    
                // adding new book to our db book list
                dbBookList.add(book);
            }
            dbAuthor.setBooks(dbBookList);
            return this.authorRepository.save(dbAuthor);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search