I am practicing JavaEE technologies. Now I am focusing in JPA with Hibernate. The project has the following entities:
Book:
@Entity @Table(name = "book")
public class Book extends BaseEntity<Long> {
@Id
private Long id;
@NotNull
private String name;
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL)
private BookDetails details;
//getters/setters
}
BookDetails:
@Entity
@Table(name = "book_details")
public class BookDetails extends BaseEntity<Long> {
@Id
private Long id;
@MapsId
@OneToOne
private Book book;
@NotNull
@Column(name = "number_of_pages")
private int numberOfPages;
//getters/setters
}
Now, the respective EJB Service classes:
BookService:
@Stateless
public class BookService extends BaseEntityService<Long, Book> {
public void createBook(Book book) {
super.getEntityManager().persist(book);
}
//update, delete, find and findAll methods
}
BookDetailsService:
@Stateless
public class BookDetailsService extends BaseEntityService<Long, BookDetails> {
public void createBookDetails(BookDetails details) {
super.getEntityManager().persist(details);
//super.persist(details); //This method would not work to persisting entity with shared Id, because it verifies if ID is null
}
//update, delete and find methods
}
The problem:
When I try to persist a new book along with its details as follows:
Book b = new Book();
b.setId(123L);
b.setName("Bible");
bookService.createBook(b);
//The entity Book is correctly persisted in the DB.
BookDetails d = new BookDetails();
d.setNumberOfPages(999);
d.setBook(b);
//b.setDetails(d); //don't do this
bookDetailsService.createBookDetails(d);
//BookDetails is not persisted in the DB, throws exception....
Throws the following exception:
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '123' for key 'PRIMARY'
The Book
entity is persisted but not the BookDetails
.
I followed this tutorials:
- Hibernate Tips: How to Share the Primary Key in a One-to-One Association
- The best way to map a @OneToOne relationship with JPA and Hibernate
Aditional Information:
- JDK 1.8
- Payara 5
- MySQL 8.0
- Hibernate 5.3.4
- OmniPersistence library. (Utilities for JPA, JDBC and DataSources)
You can look at the project repository here.