My question is very simple ..
- Let's say there are 2 classes .. Book and Author
- Let's assume that a book can ONLY be written by 1 author.
- An author can write many books.
- Let's assume author has unique name. [No 2 authors can have same name]
Now .. assuming all the hibernate\JPA configs are done.
From main method - I save Book book1 having name "book1" and author name "author1"
If I put cascade as ALL .. both book and author gets saved upon saving book.
Problem
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.
What I have done
- I have replace cascade ALL with MERGE.
- Before assigning author to book - I am checking DB for the name -
a. If I get a response - I assigned the retrieved author to the book and SAVE the book.
b. If I don't get any result - I assign the author to the book and save BOTH author and book.
This way I am able to solve my problem.
But is it the right way ?
@Entity class Book{ @Id private Long bookId; private String name; @OneToOne private Author author; } @Entity class Author{ @Id private Long authorId; private String name; } Main 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); } Update 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.
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)