【问题标题】:Exception in thread "main" org.hibernate.MappingException: Unknown entity线程“主”org.hibernate.MappingException 中的异常:未知实体
【发布时间】:2016-01-16 14:49:26
【问题描述】:

浏览 PluralSight 上的“Hibernate 简介”教程。我有这个异常错误。完整的错误是:

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.simpleprogrammer.User
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1451)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
    at com.simpleprogrammer.Program.main(Program.java:15)

不确定是什么问题。我创建了 User.java pojo。我创建了一个与 pojo 匹配的表。我创建了映射,然后将映射添加到 hibernate.cfg.xml 文件中。但是,仍然收到错误。谁能帮我解决这个问题?

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.default_schema">protein_tracker</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <mapping class="com.simpleprogrammer.User" resource="com/simpleprogrammer/User.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

程序.java

public class Program {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        Session session = HibernateUtilities.getSessionFactory().openSession();
        session.beginTransaction();

        User user = new User();
        user.setName("Joe");
        user.setGoal(250);
        session.save(user);

        session.getTransaction().commit();
        session.close();
        HibernateUtilities.getSessionFactory().close();
    }
}

用户.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 17, 2015 11:44:47 AM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.simpleprogrammer.User" table="USERS">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="total" type="int">
            <column name="TOTAL" />
        </property>
        <property name="goal" type="int">
            <column name="GOAL" />
        </property>
    </class>
</hibernate-mapping>

用户.java

package com.simpleprogrammer;

public class User {
    private int id;
    private String name;
    private int total;
    private int goal;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public int getGoal() {
        return goal;
    }
    public void setGoal(int goal) {
        this.goal = goal;
    }
}

HibernateUtilities.java

package com.simpleprogrammer;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtilities {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration().configure();

            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch(HibernateException exception) {
            System.out.println("Problem creating session factory!");
        }   
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

【问题讨论】:

  • 你在那个位置有映射 XML 吗?也只需在 cfg 文件中添加&lt;mapping resource="com/simpleprogrammer/User.hbm.xml"/&gt;
  • 是的,我确信 XML 位于该位置。我还为资源添加了一个映射标签
  • 我没有设置:(你可以尝试在路径中使用正斜杠/com/simpleprogrammer/User.hbm.xml
  • 如果教程仍然教授基于 XML 的映射而不是注释,那么它就完全过时了。查找其他教程。
  • 我的工作是使用基于 XML 的映射,所以这是不可能的

标签: java mysql sql hibernate


【解决方案1】:

LinhSaysHi,我已经使用 Hibernate 5 执行了您的代码,但我遇到了完全相同的错误。 我已经用 Hibernate 4 执行过了,没有问题。

Pluralsight 教程是为 Hibernate 4 创建的。 这是一个适用于 Hibernate 5 的会话工厂构建器:

public class HibernateUtilities_5 {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                    .configure("hibernate.cfg.xml").build();
            Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
            return metadata.getSessionFactoryBuilder().build();

        } catch (HibernateException he) {
            System.out.println("Session Factory creation failure");
            throw he;
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

【讨论】:

  • 感谢 Coli,您的解决方案就像一个魅力。但是我该如何检查呢?我的意思是如何将我的休眠版本降级到 4 并像你一样检查。如果我知道这个过程,我可以解决我的问题由于未来版本控制问题而导致的错误。提前致谢..
  • 如果你使用 Maven,你可以在 pom.xml 中指定你想要的版本。
【解决方案2】:

我在尝试使用 Hibernate 5.1.1 时也遇到了同样的错误。但是我通过用 StandardServiceRegistryBuilder 替换 ServiceRegistry 接口并使用“元数据源”来创建会话工厂来解决它。请在下面查看我的代码

static
{
    try
    {
        //Configuration configuration = new Configuration().configure();
        standardServiceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
                                    .build();
        Metadata metadata = new MetadataSources(standardServiceRegistry)
                                .getMetadataBuilder().build();
        sessionFactory = metadata.getSessionFactoryBuilder().build();

    }catch(HibernateException exception)
    {
        System.out.println("problem creating session factory!");
    }
}

public static SessionFactory getSessionFactory(){

    return sessionFactory;
}

我做了这些改变,它就像一个魅力。 请在您的代码中更改您加载配置文件的方式,然后重试。如果您仍然面临障碍,请告诉我。

【讨论】:

    【解决方案3】:

    请检查您在 MySQL 中创建的模式名称和 hibernate.cfg 文件中指定的模式名称。它对我来说不匹配,我遇到了同样的问题。

    还可以像下面这样修改连接 url,并从 hibernate.cfg 中删除默认架构字段。 jdbc:mysql://localhost:3306/protein_tracker

    这对我有用。

    【讨论】:

      【解决方案4】:

      按照 Hibernate 5 更改代码

          static
          {
              try {
                  //Configuration configuration = new Configuration().configure();
                  serviceRegistry = new 
                  StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
                                              .build();
                  Metadata metadata = new MetadataSources(serviceRegistry)
                                      .getMetadataBuilder().build();
                  sessionFactory = metadata.getSessionFactoryBuilder().build();   
              } catch (Exception e) {
                  // TODO: handle exception
                  e.printStackTrace();
              }
          }
          public static SessionFactory getSessionFactory() {
          return sessionFactory;
          }
      

      给 在 user.hbm.xml 中给出完整的类路径

           <class name="com.simpleprogrammer.Users" table="USERS">
      

      映射hibernate.cfg.xml中的资源

            <mapping resource="com/simpleprogrammer/Users.hbm.xml"/>
      

      并执行以下代码

          Session session = HibernateUtilities.getSessionFactory().openSession();
      
          session.beginTransaction();
      
          Users user = new Users();
      
          user.setuserName("Prince");
          user.setGoal(100);
          user.setId(101);
          user.setTotal(10);
      
          session.save(user);
      
          session.getTransaction().commit(); 
          session.close();
          HibernateUtilities.getSessionFactory().close();
      

      【讨论】:

        【解决方案5】:

        映射有点问题。确保您指定的路径是正确的。 当我遇到同样的问题时,我只将 hibernate.cfg.xml 中的映射重新修改为

        <mapping class="com.simpleprogrammer.User"/>
        

        没有添加资源等其他属性

        【讨论】:

          【解决方案6】:

          我使用了您的示例,并且能够通过一些小的调整使其工作。

          验证 User.hbm.xml 位于 src/main/resources/com/simpleprogrammer。改为小写table="users"

          然后在hibernate.cfg.xml中:

          1. 从 session-factory 中删除了 name="" 属性。
          2. 添加了<property name="hibernate.connection.password">SomePassword</property>
          3. 已添加&lt;property name="hibernate.hbm2ddl.auto"&gt;create&lt;/property&gt;

          【讨论】:

            【解决方案7】:

            Hibernate jar 有问题... 在这里我可以看到你正在使用 Hibernate 4....来开发项目... 所以添加hibernate 4.3.5 jar它应该可以工作............

            如果你不使用元数据,最好使用 hibernate 4.3 jar

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-06-09
              • 2016-03-01
              • 2017-06-03
              • 2023-03-19
              • 1970-01-01
              • 1970-01-01
              • 2012-02-19
              • 2014-09-01
              相关资源
              最近更新 更多