title: Hibernate | Spring Data JPA | @OneToOne
body: <p>My question is very simple .. </p>
  
  <ol>
  <li>Let's say there are 2 classes ..  Book and Author </li>
  <li>Let's assume that a book can ONLY be written by 1 author.</li>
  <li>An author can write many books.</li>
  <li>Let's assume author has unique name. [No 2 authors can have same name]</li>
  </ol>
  
  <p>Now .. assuming all the hibernate\JPA configs are done.</p>
  
  <p>From main method - I save Book book1 having name "book1" and author name "author1"</p>
  
  <p>If I put cascade as ALL .. both book and author gets saved upon saving book.</p>
  
  <p><strong>Problem</strong></p>
  
  <p>Now, If I save another book with same author - it is saving both book and author again. This means I am ending up with 2 same authors.</p>
  
  <p><strong>What I have done</strong></p>
  
  <ol>
  <li>I have replace cascade ALL with MERGE.</li>
  <li>Before assigning author to book - I am checking DB for the name - </li>
  </ol>
  
  <p>a. If I get a response - I assigned the retrieved author to the book and SAVE the book.</p>
  
  <p>b. If I don't get any result - I assign the author to the book and save BOTH author and book.</p>
  
  <p>This way I am able to solve my problem.</p>
  
  <p>But is it the right way ?</p>
  
  <pre><code>@Entity 
  class Book{
  
      @Id
      private Long bookId;
  
      private String name;
  
      @OneToOne
      private Author author;
  
  }
  
  @Entity
  class Author{
  
      @Id
      private Long authorId;
      private String name;
  
  }
  </code></pre>
  
  <hr>
  
  <p>Main Code </p>
  
  <pre><code>public static void main(String[] args) {
      ApplicationContext context = SpringApplication.run(BeanConfiguration.class, args);
      BookRepository bookRepo = context.getBean(BookRepository.class);
      AuthorRepository authorRepo = context.getBean(AuthorRepository.class);
  
      Book b1 = new Book();
      b1.setBookName("book1");
  
      Author a1 = new Author();
      a1.setAuthorName("author1");
  
      Author authorFromDatabase = authorRepo.findByAuthorName(a1.getAuthorName());
      if (authorFromDatabase == null) {
          b1.setAuthor(a1);
          authorRepo.save(a1);
      } else {
          b1.setAuthor(authorFromDatabase);
      }
      bookRepo.save(b1);
  }
  </code></pre>
  
  <p><strong>Update</strong>
  It is not that simple.. For example .. Please think about the association between .. Customer and Address .. customer can have one or many address .. and if a new customer is sharing address with other customer .. then don't make the persist on address .. just assign the the address(id) to the new customer. </p>
  
  <p>My question is what i did above , i.e. to search for existing author (or address in above case) is the right approach ? .. to avoid duplicate rows in the Author (or Address table)  </p>