【发布时间】:2019-02-01 00:40:31
【问题描述】:
我正在练习 JavaEE 技术。现在我专注于使用 Hibernate 的 JPA。该项目有以下实体:
书籍:
@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
}
书籍详情:
@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
}
现在,各个 EJB 服务类:
图书服务:
@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
}
问题:
当我尝试保留一本新书及其详细信息时:
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....
抛出以下异常:
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '123' for key 'PRIMARY'
Book 实体是持久化的,但不是BookDetails。
我遵循了这个教程:
- 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
其他信息:
- JDK 1.8
- 帕亚拉 5
- MySQL 8.0
- 休眠 5.3.4
- OmniPersistence 图书馆。 (适用于 JPA、JDBC 和数据源的实用程序)
您可以查看项目存储库here。
【问题讨论】:
-
你可以在这里看到它:docs.jboss.org/hibernate/orm/5.3/userguide/html_single/… 无论如何,我会尝试使用@PrimaryKeyJoinColumn 注释。
-
@NathanHughes 虽然我用
@PrimaryKeyJoinColumn替换了@MapsId,但它仍然不起作用。但是,异常更改为:java.sql.SQLException: Field 'book_id' doesn't have a default value。所以我尝试设置BookDetails(d.setId(b.getId()))的id,但仍然显示相同的错误。
标签: java hibernate jpa jakarta-ee