hibernate 线程“main”中出现异常,未知实体

yv5phkfx  于 2022-11-24  发布在  其他
关注(0)|答案(8)|浏览(213)

在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匹配的表。我创建了Map,然后将Map添加到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>

Program.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();
    }
}

User.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>

User.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;
    }
}
iih3973s

iih3973s1#

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

bkhjykvo2#

我在使用Hibernate 5.1.1进行测试时也遇到了同样的错误,但我通过用StandardServiceRegistryBuilder替换ServiceRegistry接口并使用“metadatasources”创建会话工厂来解决这个问题。

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

我做了这些更改,它的工作就像一个魅力。请在您的代码中作出改变,以您加载配置文件的方式,并再次尝试。让我知道,如果你仍然面临障碍。

guykilcj

guykilcj3#

请检查您在MySQL中创建的模式名称和在hibernate.cfg文件中指定的模式名称。它对我来说不匹配,我遇到了同样的问题。
同时修改如下所示的连接URL,并从hibernate.cfg. jdbc:mysql://localhost:3306/protein_tracker中删除默认模式字段
这对我很管用。

vmjh9lq9

vmjh9lq94#

根据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">

Maphibernate.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();
42fyovps

42fyovps5#

Map有一个小问题。请确保您指定的路径是正确的。当我遇到同样的问题时,我只是重新修改了hibernate.cfg.xml中的Map以

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

未添加资源等其他属性

brqmpdu1

brqmpdu16#

我用了你的例子,并能够得到它的工作与一些小的调整。
已验证User.hbm.xml是否位于src/main/resources/com/simpleprogrammer中。已更改为小写table="users"
然后在hibernate.cfg.xml中:
1.已从会话工厂中删除name=""属性。
1.添加了一个<property name="hibernate.connection.password">SomePassword</property>
1.添加的<property name="hibernate.hbm2ddl.auto">create</property>

y1aodyip

y1aodyip7#

公司名称:上海市力博科技有限公司工作地点:上海市发布时间:2009 - 4 - 11
如果你不使用元数据,最好使用Hibernate 4.3 jar

mbjcgjjk

mbjcgjjk8#

简单的解决方案是,当你创建SessionFactory对象时,只需要检查你已经创建的HibernateUtil类。编写正确的hibernateUtility类并导入正确的包。如果你在一个项目中创建了多个src包,那么请为hibernateUtility类保留不同的包名。

相关问题