在学习 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"/>
我无法弄清楚为什么会抛出该异常。 非常感谢。
答案 0 :(得分:0)
正如所指出的那样here:
<块引用><mapping package="..."/>
条目用于配置在包本身上定义的元数据,而不是用于该包中的类。
因此,您应该使用上述问题中提出的一些解决方案或明确提供 hibernate.cfg.xml
中所有实体的列表:
<mapping class="com.mycompany.mavenproject1.entity.Book"/>
<!-- other entities -->
答案 1 :(得分:0)
发现自 Hibernate 5.x 以来已经实施了一些更改的提示。
使用此代码,教程运行良好。
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources(standardRegistry)
.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder().build();