Hibernate 5 :- org.hibernate.MappingException: Unknown entity

2022-09-03 17:16:56

当我尝试将休眠5.0与mysql集成时收到错误消息org.hibernate.MappingException: Unknown entity

这似乎是hibernate5.0.0和5.0.1的问题。这在休眠 4.3.9 中工作正常

Maven dependices

<dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
</dependency>

休眠.cfg.xml

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3307/SampleDB
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <mapping class="UserA.User"></mapping>

</session-factory>

HibernateMain.java 代码

package UserA;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Map;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.ServiceRegistry;

public class HibernateMain {

    public static void main(String[] args) {

        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

        SessionFactory sf = configuration.buildSessionFactory(sr);




        User user1 = new User();
        user1.setUserName("Arpit");
        user1.setUserMessage("Hello world from arpit");
        user1.setUserId(22);

        Session ss = sf.openSession();
        ss.beginTransaction();
        // saving objects to session
        ss.save(user1);
        ss.getTransaction().commit();
        ss.close();

    }

}

用户.java

package UserA;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name="User_table")
public class User {
    @Id
    int userId;
    @Column(name = "User_Name")
    String userName;

    @Column(name = "User_Message")
    String userMessage;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserMessage() {
        return userMessage;
    }

    public void setUserMessage(String userMessage) {
        this.userMessage = userMessage;
    }

}

答案 1

我已经修复了Hibernate 5的相同问题。此代码中存在问题

Configuration configuration = new Configuration();
configuration.configure();

ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(
    configuration.getProperties()).build();

SessionFactory sf = configuration.buildSessionFactory(sr);

此代码适用于 Hibernate 4.3.5,但相同的代码对于 Hibernate 5 具有相同的问题。

当您这样做时,使用Hibernate 5,会丢失有关通过调用获取的映射的所有信息。configuration.buildSessionFactory(sr)Configurationconfiguration.configure()

溶液

要解决此问题,如果使用标准配置文件 和 ,则可以通过这种方式创建会话工厂(不带hibernate.cfg.xmlhibernate.propertiesServiceRegistry)

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

加载属性

如果您在其他文件中具有属性,则可以使用以下方法构建会话工厂(无论如何,如果您有和其他文件,它将同时加载)hibernate.propertiesStandardServiceRegistryBuilderhibernate.properties

将属性作为资源加载

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
    configure().loadProperties("hibernate-h2.properties").build();
SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);  

您需要在类路径(源文件夹的根目录,资源文件夹)中具有。您也可以指定根源文件夹的路径。hibernate-h2.properties/com/github/xxx/model/hibernate-h2.properties

从文件系统中的路径加载属性

File propertiesPath = new File("some_path");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
    configure().loadProperties(propertiesPath).build();
SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);

您可以在此处找到使用此方法的示例控制台应用程序 fluent-hibernate-mysql。它使用实用程序类从 fluent-hibernate 库构建会话工厂。

不正确的休眠 5 教程

在 Hibernate 5 教程 1.1.6 中有一个不正确的示例。启动和助手。它使用此代码

 return new Configuration().configure().buildSessionFactory(
                new StandardServiceRegistryBuilder().build() );

它没有进行正确的配置。


答案 2

在Hibernate 5中,您需要构建和构建。您可以使用以下内容来构建 。 应位于应用程序类路径的根目录中。StandardServiceRegistryMetadataSessionFactoryHibernateUtilSessionFactoryhibernate.cfg.xml

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml").build();
            Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
            return metadata.getSessionFactoryBuilder().build();
        } 
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

此外,如果您使用的是Hibernate 5并用作标识符生成策略,那么使用将默认使用MySQL获取“序列”身份生成器,如果您未在标识符属性的实体中配置它,这将为您提供例外。因此,对于Hibernate 5,请改用。@IdGenerationType.AUTOcom.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'SampleDB.hibernate_sequence' doesn't existGenerationType.IDENTITY


推荐