【问题标题】:Hibernate Mapping Exception error: Unknown entity休眠映射异常错误:未知实体
【发布时间】: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"/>

我无法弄清楚为什么会引发该异常。 非常感谢。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    正如上面提到的here

    &lt;mapping package="..."/&gt; 条目用于配置在包本身上定义的元数据,而不是用于该包中的类。

    因此,您应该使用上述问题中提出的一些解决方案,或者在hibernate.cfg.xml 中明确提供所有实体的列表:

    <mapping class="com.mycompany.mavenproject1.entity.Book"/>
    <!--  other entities  -->
    

    【讨论】:

    • 也试过了,但给了我同样的错误信息。
    • 你在Book上使用@javax.persistence.Entity注解吗?
    • 是的,我就是这么写的。
    【解决方案2】:

    发现自 Hibernate 5.x 以来已经实施了一些更改。

    使用此代码,教程运行良好。

    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                    .configure()
                    .build();
    
            Metadata metadata = new MetadataSources(standardRegistry)
                    .getMetadataBuilder()
                    .build();
    
            return metadata.getSessionFactoryBuilder().build();
    

    【讨论】:

      猜你喜欢
      • 2017-01-22
      • 1970-01-01
      • 2016-10-18
      • 2019-12-03
      • 2020-12-18
      • 2016-02-05
      • 2012-03-11
      • 1970-01-01
      相关资源
      最近更新 更多