【发布时间】:2021-05-29 14:08:10
【问题描述】:
在学习 Hibernate 和相关的设计模式 (https://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-jpa-dao-example/) 时,我遇到了 org.hibernate.MappingException: Unknown entity: com.mycompany.mavenproject1.entity.Book 的问题。
使用带有嵌入式 HSQLDB 的最新 Hibernate 进行学习。
使用带注释的实体文件
@Entity
@Table(name = "book")
public class Book {
@Id
@Column(name = "id")
private String id;
...
bookDAO
private static SessionFactory getSessionFactory() {
try {
// Build a SessionFactory object from session-factory config
// defined in the hibernate.cfg.xml file.
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
} catch (Throwable e) {
System.err.println("Error in creating SessionFactory object."
+ e.getMessage());
throw new ExceptionInInitializerError(e);
}
}
public void persist(Book entity) {
getCurrentSession().save(entity);
}
图书服务
public void persist(Book entity) {
bookDao.openCurrentSessionwithTransaction();
bookDao.persist(entity);
bookDao.closeCurrentSessionwithTransaction();
}
应用程序
BookService bookService = new BookService();
Book book1 = new Book("1", "The Brothers Karamazov", "Fyodor Dostoevsky");
bookService.persist(book1);
hibernate.cfg.xml
<property name="hibernate.current_session_context_class">thread</property>
<mapping package="com.mycompany.mavenproject1.entity"/>
我无法弄清楚为什么会引发该异常。 非常感谢。
【问题讨论】: