gpt4 book ai didi

java - EntityManager 抛出 @OnetoMany 映射异常

转载 作者:行者123 更新时间:2023-12-02 06:19:59 25 4
gpt4 key购买 nike

我目前正在尝试以双向关系映射这两个实体,但出现如图所示的异常。实体

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;
}

...
}

作者.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):

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)

有什么想法吗?

最佳答案

引用this post了解如何使用JoinColumn

详细说明:您的 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 实体的示例)。

关于java - EntityManager 抛出 @OnetoMany 映射异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21097133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com