简体   繁体   中英

How to fix Hibernate Unknown entity exception?

I have HibernateSesstion factory class for getting sesion

public class HibernateSessionFactory {

    private static SessionFactory sessionFactory = buildSessionFactory();

    protected static SessionFactory buildSessionFactory(){

        Configuration configuration = new Configuration();
        ServiceRegistry registry = new StandardServiceRegistryBuilder()
                .loadProperties("hibernate.properties").build();
        try {
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        }catch (Exception e){
            StandardServiceRegistryBuilder.destroy(registry);
            e.printStackTrace();
        }
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory(){
        if (sessionFactory.isClosed()){
            buildSessionFactory();
        }
        return sessionFactory;
    }

My entity class

@Entity()
@Table(name = "user_commands")
public class UserCommands implements Serializable {

    @Id
    @Column(name = "chat_id")
    private Long chatId;
    @Column(name = "last_command")
    private String lastCommand;

    public Long getChatId() {
        return chatId;
    }

    public void setChatId(Long chatId) {
        this.chatId = chatId;
    }

    public String getLastCommand() {
        return lastCommand;
    }

    public void setLastCommand(String lastCommand) {
        this.lastCommand = lastCommand;
    }
}

And my function from class UserCommandsRepository which select some data

String sql = "update user_commands set last_command = :lastCommand where chat_id = :chatId";
Session session = HibernateSessionFactory.getSessionFactory().openSession();
session.beginTransaction();
session.saveOrUpdate(userCommands);
session.getTransaction().commit();
session.close();

My hibernate.property file

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://URL
hibernate.connection.username=USERNAME
hibernate.connection.password=PASSWORD
hibernate.show_sql=true
hibernate.hbm2ddl=update

When I am trying to run my Main.java class, it's failing with error

Exception in thread "main" org.hibernate.MappingException: Unknown entity: entity.UserCommands
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:704)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1609)
    at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:293)
    at org.hibernate.event.internal.EntityState.getEntityState(EntityState.java:59)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:85)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:617)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:610)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:605)
    at repository.UserCommandsRepository.updateLastUserCommand(UserCommandsRepository.java:13)
    at highwayMotorsTelergramBot.Main.main(Main.java:26)

You never tell Hibernate about your entity models. There are several ways to do this. You can do this via XML, the Configuration object or the Session object.

Check this for more org.hibernate.MappingException: Unknown entity: annotations.Users

As it stated in the documentation the Configuration is semi-deprecated:

Configuration is semi-deprecated but still available for use, in a limited form that eliminates these drawbacks. "Under the covers", Configuration uses the new bootstrapping code, so the things available there are also available here in terms of auto-discovery.

  1. You can use new native bootstrapping api in the following way:
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .loadProperties("hibernate.properties")
    .build();
MetadataSources metadata = new MetadataSources(serviceRegistry);
metadata.addAnnotatedClass(UserCommands.class);
// ...
Metadata meta = metadata.buildMetadata();
SessionFactory sessionFactory = meta.buildSessionFactory();
  1. You can use jpa bootstrapping in the following way:
HibernatePersistenceProvider provider = new HibernatePersistenceProvider();
EntityManagerFactory emFactory = provider.createEntityManagerFactory("CRM", null);

EntityManager em = emFactory.createEntityManager();
// ...

This assumes that you have META-INF folder in your class path and this folder contains the persistence.xml file like the following:

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="CRM">
        <description>Persistence unit for Hibernate User Guide</description>
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>


        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://URL" />
            <property name="javax.persistence.jdbc.user" value="USERNAME" />
            <property name="javax.persistence.jdbc.password" value="PASSWORD" />
            
            <property name="hibernate.default_schema" value="TEST_SCHEMA" />
            
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.use_sql_comments" value="true" />
        </properties>
    </persistence-unit>
</persistence>

In this case you should not manually list all your entities hibernate will pick up them automatically if they lies in the same jar with persistence.xml file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM