我目前正在尝试以双向关系映射这两个实体,但如图所示获得异常。实体
Book.java:
@Entity
@Table(name = "Book")
public class Book {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="bookId")
private Collection<Author> authors;
public Collection<Author> getAuthors() {
return authors;
}
...
}
Author.java:
@Entity
public class Author {
@Id
@GeneratedValue
@Column(name="id")
private Long id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="author_id")
private Long bookId;
...
}
例外:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: BookStore] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:889)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:56)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at org.hibstore.dao.DAOTest.main(DAOTest.java:10)
Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on org.hibstore.domain.Author.bookId references an unknown entity: java.lang.Long
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:109)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1514)
有什么想法吗?
答案 0 :(得分:2)
有关如何使用JoinColumn
的信息,请参阅this post。
详细说明:您的Author
实体必须指向Book
实体,而不是其ID。这是使用JPA的优势:您使用实体,而不是键。
以下是一个例子:
@Entity
@Table(name = "Book")
public class Book {
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="book")
private Collection<Author> authors;
// ...
}
@Entity
public class Author {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="book_id")
private Book book;
// ...
}
为什么每个作者都会有一本书(这里的连接专栏指向这本书)是有问题的,你应该重新思考你的数据模型:多对多关系可能更有意义,但你需要第三个表格(有关如何相应地设置JPA实体的示例)。
答案 1 :(得分:0)
对于简单关系,我建议您浏览以下链接http://www.objectdb.com/api/java/jpa/annotations/relationship。
尝试理解ORM提供的错误消息..
org.hibstore.domain.Author.bookId references an unknown entity: java.lang.Long
ORM说Long(Author.bookId)不是实体。是的,因为您试图关联字段而不是注释为实体的对象。您必须提供“预订”类型而不是bookid。
更改为
private Book book;
注意**,我刚给出了异常的解决方案,你也必须在Book中更改你的声明。但我希望你理解概念并自我修复,而不是在这里指出答案..