Hibernate 5:——org.hibernate。MappingException:未知的实体

时间:2022-02-17 19:11:33

I am getting the error message org.hibernate.MappingException: Unknown entity when i am trying to integrate hibernate 5.0 with mysql

我正在获取错误消息org.hibernate。MappingException:当我尝试将hibernate 5.0与mysql集成时,未知实体

This seems to be an issue with hibernate5.0.0 and 5.0.1 . This works fine with hibernate 4.3.9

这似乎是hibernate5.0.0和5.0.1的问题。这对hibernate 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>

hibernate.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 code

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();

    }

}

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

}

7 个解决方案

#1


23  

I have fixed the same issue with Hibernate 5. There is a problem in this code

我已经修复了Hibernate 5的相同问题。这段代码有一个问题

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

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

SessionFactory sf = configuration.buildSessionFactory(sr);

This code works fine for Hibernate 4.3.5, but the same code has the same issue for Hibernate 5.

这段代码适用于Hibernate 4.3.5,但是相同的代码对于Hibernate 5也有同样的问题。

When you do configuration.buildSessionFactory(sr), using Hibernate 5, Configuration losts all information about mapping that gets by call configuration.configure().

在使用Hibernate 5进行Configuration . buildsessionfactory (sr)时,配置会丢失通过call Configuration .configure()获得的所有有关映射的信息。

Solution

解决方案

To fix the issue, if you use standard configuration files hibernate.cfg.xml and hibernate.properties, you can create the session factory by this way (without ServiceRegistry)

为了解决这个问题,如果您使用标准配置文件hibernate.cfg。xml和hibernate。属性,您可以通过这种方式创建会话工厂(没有ServiceRegistry)

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

Loading properties

加载属性

If you have properties in a file other then hibernate.properties, you can build session factory using StandardServiceRegistryBuilder (anyway, if you have hibernate.properties and other file, it will be loaded both)

如果在另一个文件中有属性,那么hibernate。属性,您可以使用标准serviceregistrybuilder构建会话工厂(无论如何,如果您有hibernate的话)。属性和其他文件,它将同时载入

To load properties as a resource

将属性作为资源加载

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

You need to have hibernate-h2.properties in the class path (root of the sources folder, resources folder). You can specify a path from the root source folder too /com/github/xxx/model/hibernate-h2.properties.

你需要冬眠。类路径中的属性(源文件夹、资源文件夹的根)。您也可以从根源文件夹中指定路径/ com/github/xxx/model/hibernat-h2 .properties。

To load properties from a path in the file system

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

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

You can find an example console application using this approach here fluent-hibernate-mysql. It uses a utility class to build the session factory from the fluent-hibernate library.

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

Incorrect Hibernate 5 tutorial

不正确的Hibernate 5教程

There is an incorrect example in Hibernate 5 tutorial 1.1.6. Startup and helpers. It uses this code

在Hibernate 5教程1.1.6中有一个错误的示例。启动和帮手。它使用这个代码

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

It doesn't do a proper configuration.

它没有正确的构型。

#2


6  

In Hibernate 5, you need to build StandardServiceRegistry and Metadata to build SessionFactory. You could use the following HibernateUtil to build SessionFactory. hibernate.cfg.xml should be in the root of the classpath of your application.

在Hibernate 5中,需要构建serviceregistry和元数据来构建SessionFactory。您可以使用下面的HibernateUtil来构建SessionFactory。hibernate.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;
    }

}

Also, If you're using Hibernate 5 and using @Id as your identifier generation strategy then using GenerationType.AUTO will pick up the "sequence" identity generator by default with MySQL, which will give you an the com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'SampleDB.hibernate_sequence' doesn't exist exception, if you don't have it configured in your entities at identifier attributes. So with Hibernate 5, use GenerationType.IDENTITY instead.

此外,如果您使用Hibernate 5并使用@Id作为标识符生成策略,则使用GenerationType。AUTO将在默认情况下使用MySQL获取“sequence”标识生成器,这将为您提供com.mysql.jdbc.exceptions.jdbc4。SampleDB MySQLSyntaxErrorException:表”。hibernate_sequence'不存在异常,如果您没有在实体中的标识符属性中配置它的话。所以使用Hibernate 5,使用GenerationType。身份。

#3


0  

You didn't add a configuration file

您没有添加配置文件。

configuration.configure("/hibernate.cfg.xml");

#4


0  

Please make sure that you have created mapping file User.hbm.xml or User.xml file and included that file in hibernate.cfg.xml

请确保您已经创建了mapping file User.hbm。xml或用户。xml文件,并将该文件包含在hibernate.cfg.xml中。

#5


0  

I think this is a easy way to solve this problem.

我认为这是解决这个问题的简单方法。

@Entity
@Table(name="User_table")

public class User {

    @Id
    int userId;

    @Column(name = "User_Name")
    String userName;
.................

#6


0  

Using this:

用这个:

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

Session session = sessionFactory.openSession();

instead of this:

而不是:

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

Session session = factory.openSession();

solved the issue with Hibernate 5.2.10.Final.

最终解决了Hibernate 5.2.10.10的问题。

#7


0  

I was facing the same issue & I searched for almost 2 hours and tried with different possible ways like replacing old hibernate jars&changing the db table schema. But finally got the solution as below;

我面临着同样的问题&我搜索了将近2个小时,尝试了不同的方法,比如替换旧的hibernate jars&change数据库表模式。但最终得到如下解;

 //This line to be replaced with below commented line
 SessionFactory factory = new Configuration().configure().buildSessionFactory();

Replace above for

替换上面

Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);

It will then work fine..

然后它就会正常工作。

#1


23  

I have fixed the same issue with Hibernate 5. There is a problem in this code

我已经修复了Hibernate 5的相同问题。这段代码有一个问题

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

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

SessionFactory sf = configuration.buildSessionFactory(sr);

This code works fine for Hibernate 4.3.5, but the same code has the same issue for Hibernate 5.

这段代码适用于Hibernate 4.3.5,但是相同的代码对于Hibernate 5也有同样的问题。

When you do configuration.buildSessionFactory(sr), using Hibernate 5, Configuration losts all information about mapping that gets by call configuration.configure().

在使用Hibernate 5进行Configuration . buildsessionfactory (sr)时,配置会丢失通过call Configuration .configure()获得的所有有关映射的信息。

Solution

解决方案

To fix the issue, if you use standard configuration files hibernate.cfg.xml and hibernate.properties, you can create the session factory by this way (without ServiceRegistry)

为了解决这个问题,如果您使用标准配置文件hibernate.cfg。xml和hibernate。属性,您可以通过这种方式创建会话工厂(没有ServiceRegistry)

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

Loading properties

加载属性

If you have properties in a file other then hibernate.properties, you can build session factory using StandardServiceRegistryBuilder (anyway, if you have hibernate.properties and other file, it will be loaded both)

如果在另一个文件中有属性,那么hibernate。属性,您可以使用标准serviceregistrybuilder构建会话工厂(无论如何,如果您有hibernate的话)。属性和其他文件,它将同时载入

To load properties as a resource

将属性作为资源加载

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

You need to have hibernate-h2.properties in the class path (root of the sources folder, resources folder). You can specify a path from the root source folder too /com/github/xxx/model/hibernate-h2.properties.

你需要冬眠。类路径中的属性(源文件夹、资源文件夹的根)。您也可以从根源文件夹中指定路径/ com/github/xxx/model/hibernat-h2 .properties。

To load properties from a path in the file system

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

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

You can find an example console application using this approach here fluent-hibernate-mysql. It uses a utility class to build the session factory from the fluent-hibernate library.

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

Incorrect Hibernate 5 tutorial

不正确的Hibernate 5教程

There is an incorrect example in Hibernate 5 tutorial 1.1.6. Startup and helpers. It uses this code

在Hibernate 5教程1.1.6中有一个错误的示例。启动和帮手。它使用这个代码

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

It doesn't do a proper configuration.

它没有正确的构型。

#2


6  

In Hibernate 5, you need to build StandardServiceRegistry and Metadata to build SessionFactory. You could use the following HibernateUtil to build SessionFactory. hibernate.cfg.xml should be in the root of the classpath of your application.

在Hibernate 5中,需要构建serviceregistry和元数据来构建SessionFactory。您可以使用下面的HibernateUtil来构建SessionFactory。hibernate.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;
    }

}

Also, If you're using Hibernate 5 and using @Id as your identifier generation strategy then using GenerationType.AUTO will pick up the "sequence" identity generator by default with MySQL, which will give you an the com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'SampleDB.hibernate_sequence' doesn't exist exception, if you don't have it configured in your entities at identifier attributes. So with Hibernate 5, use GenerationType.IDENTITY instead.

此外,如果您使用Hibernate 5并使用@Id作为标识符生成策略,则使用GenerationType。AUTO将在默认情况下使用MySQL获取“sequence”标识生成器,这将为您提供com.mysql.jdbc.exceptions.jdbc4。SampleDB MySQLSyntaxErrorException:表”。hibernate_sequence'不存在异常,如果您没有在实体中的标识符属性中配置它的话。所以使用Hibernate 5,使用GenerationType。身份。

#3


0  

You didn't add a configuration file

您没有添加配置文件。

configuration.configure("/hibernate.cfg.xml");

#4


0  

Please make sure that you have created mapping file User.hbm.xml or User.xml file and included that file in hibernate.cfg.xml

请确保您已经创建了mapping file User.hbm。xml或用户。xml文件,并将该文件包含在hibernate.cfg.xml中。

#5


0  

I think this is a easy way to solve this problem.

我认为这是解决这个问题的简单方法。

@Entity
@Table(name="User_table")

public class User {

    @Id
    int userId;

    @Column(name = "User_Name")
    String userName;
.................

#6


0  

Using this:

用这个:

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

Session session = sessionFactory.openSession();

instead of this:

而不是:

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

Session session = factory.openSession();

solved the issue with Hibernate 5.2.10.Final.

最终解决了Hibernate 5.2.10.10的问题。

#7


0  

I was facing the same issue & I searched for almost 2 hours and tried with different possible ways like replacing old hibernate jars&changing the db table schema. But finally got the solution as below;

我面临着同样的问题&我搜索了将近2个小时,尝试了不同的方法,比如替换旧的hibernate jars&change数据库表模式。但最终得到如下解;

 //This line to be replaced with below commented line
 SessionFactory factory = new Configuration().configure().buildSessionFactory();

Replace above for

替换上面

Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);

It will then work fine..

然后它就会正常工作。