带注释的类+ cfg.xml = org.hibernate.MappingException:未知实体

时间:2018-06-26 08:26:34

标签: hibernate mappingexception

这个问题在这里已经被描述过很多次了,但是我没有看到有效的建议来消除它。

这里有两个相同的问题,没有答案:

  1. org.hibernate.MappingException: Unknown entity
  2. Hibernate error - org.hibernate.MappingException: Unknown entity:

我将再次描述问题。

一个简单的教程应用程序。

hibernate-core-5.3.1.Final

hibernate-annotations-3.5.6-最终

hibernate-jpa-2.0-api-1.0.0.Final

...

主班

package main;

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

public class Main {
    public static void main(String[] args) {
        Configuration conf = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
        builder.applySettings(conf.getProperties());
        ServiceRegistry registry = builder.build();
        SessionFactory sessionFactory = conf.buildSessionFactory(registry);

        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        Employee employee = new Employee();
        employee.setFirstName("John");
        employee.setLastName("Doe");
        employee.setSalary(1000000);

        session.save(employee);
        transaction.commit();
        sessionFactory.close();
    }
}

员工类别

package main;

import javax.persistence.*;

@Entity
@Table(name="EMPLOYEE")
public class Employee {
    @Id
    @GeneratedValue
    @Column(name = "ID")
    private int id;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "SALARY")
    private int salary;

    public Employee() {}

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
}

hibernate.cfg.xml文件

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.verifyServerCertificate">false</property>
        <property name="hibernate.connection.useSSL">true</property>
        <property name="hibernate.connection.requireSSL">false</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.format_sql">true</property>
        <mapping class="main.Employee"/>
    </session-factory>
</hibernate-configuration>

例外

...

INFO: HHH10001001: Connection properties: {user=root, password=****, verifyServerCertificate=false, useSSL=true, requireSSL=false}
Jun 26, 2018 10:54:38 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jun 26, 2018 10:54:38 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jun 26, 2018 10:54:38 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Jun 26, 2018 10:54:39 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@5026735c'
Exception in thread "main" org.hibernate.MappingException: Unknown entity: main.Employee
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:684)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1692)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
    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:709)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:701)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:696)
    at main.Main.main(Main.java:26)

@Entity存在

存在映射class="main.Employee"

我要求帮助确定问题的原因。 请不要使用configuration.addAnnotatedClass(Employee.class)和创建hbm文件。 我尝试过这些选项,它们起作用。 我对上述情况特别感兴趣。

1 个答案:

答案 0 :(得分:0)

  • 您正在使用hibernate 5.3.1,因此您不需要hibernate-annotations-3.5.6-Final。
  • 对于休眠5,声明以下类:

    import org.hibernate.SessionFactory;
    
    import org.hibernate.boot.MetadataSources;
    
    import org.hibernate.boot.registry.StandardServiceRegistry;
    
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    
    public class HibernateUtil {
    
    private static final SessionFactory sessionFactory = 
    buildSessionFactory();
    
    private static SessionFactory buildSessionFactory() {
    
    try {
     final StandardServiceRegistry registry = new 
     StandardServiceRegistryBuilder()
            .configure() // configures settings from hibernate.cfg.xml
            .build();
    
        return new MetadataSources( registry ).buildMetadata().buildSessionFactory();
    
    }catch(Exception e) {   
    
        e.printStackTrace();
    
        throw new RuntimeException("There was an error building the factory...!");
    }
    

    }

    public static SessionFactory getSessionFactory() {
         return sessionFactory;
     }
    

    }

  • 在您的主要方法中:

    Session session = HibernateUtil.getSessionFactory().openSession();