Saif ullah Minhas
Saif ullah Minhas

Reputation: 97

Hibernate Mapping Exception [Tried previous solutions]

I am trying to run a maven based Hibernate Hello World Project. I have done every step right but it is giving Hibernate Mapping Exception: Unknown Entity. I have already declared mapping of my Entity class in Hibernate.cfg.xml.

Here is my configuration file code.

<?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>


    <!-- Database connection settings -->

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/test
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

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

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

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

    <!-- Drop and re-create the database schema on startup
         if table isn't present hibernate will create the table -->
    <property name="hbm2ddl.auto">create</property>

    <property name="hibernate.current_session_context_class">thread</property>
    <mapping class="com.openlibrary.model.Book"/>


</session-factory>
</hibernate-configuration>

Here is Session Factory code

public static SessionFactory getSessionFactory() {

    if (sessionFactory == null) {

        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    }
    return sessionFactory;
}

And my model class package com.openlibrary.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Book {
    @Id
    @GeneratedValue
    int bookID;
    String bookName;

    public int getBookID() {
        return bookID;
    }

    public void setBookID(int bookID) {
        this.bookID = bookID;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
}

And here is the exception

Exception in thread "main" org.hibernate.UnknownEntityTypeException: Unable to locate persister: com.openlibrary.model.Book
at org.hibernate.internal.SessionFactoryImpl.locateEntityPersister(SessionFactoryImpl.java:787)
at org.hibernate.internal.SessionImpl.locateEntityPersister(SessionImpl.java:2637)
at org.hibernate.internal.SessionImpl.access$2500(SessionImpl.java:164)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2575)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2562)
at org.hibernate.internal.SessionImpl.byId(SessionImpl.java:1044)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
at com.openlibrary.dao.BookDAO.getBookById(BookDAO.java:43)
at com.openlibrary.test.Testing.main(Testing.java:22)

I know such question has been asked before But I am unable to understand why hibernate throws exception when mapping is already done. I did it last time almost a year back. It was working the same way. Need help here.

Now there is a little twist in scenario. I bypassed the exception by changing my maven dependency of hibernate-core. I was getting the exception with this dependency. It was latest on maven website.

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.0.0.CR2</version>
 </dependency>

I changed the version to 4.3.7.Final. Then there was no exception. I dont know why it is throwing exception. Maybe someone can explain. I will really appreciate that.

Upvotes: 2

Views: 3250

Answers (7)

djg
djg

Reputation: 129

For me it was the fact that at some point hibernate started using the annotations from jakarta.persistence.* as opposed to java.persistence.*

Upvotes: 0

Abdelhak
Abdelhak

Reputation: 8387

Obviously you should add, but doesn't have impact:

  public class Book implements Serializable{
   }          

But when I changed the version to 4.3.7.Final. Then there was no exception.

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.7.Final</version>
   </dependency>

Upvotes: 0

Ranjeet
Ranjeet

Reputation: 634

-Your Book Model class is not implemented Serializable interface.

-Try with below code.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

    @Entity
    public class Book implements Serializable {
        @Id
        @GeneratedValue
        int bookID;
        String bookName;

        public int getBookID() {
            return bookID;
        }

        public void setBookID(int bookID) {
            this.bookID = bookID;
        }

        public String getBookName() {
            return bookName;
        }

        public void setBookName(String bookName) {
            this.bookName = bookName;
        }
    }

Upvotes: 0

osama yaccoub
osama yaccoub

Reputation: 1866

Don't use Configuration with StandardServiceRegistryBuilder, Configuration is considered deprecated, but instead make the bootstrapping as mentioned in the hibernate 5 documentation, I had the same problem and this fixed it.

StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure( "org/hibernate/example/MyCfg.xml" )
.build();

Metadata metadata = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" )
.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
.build();

SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
.applyBeanManager( getBeanManagerFromSomewhere() )
.build();

for further details , check the documentation

Upvotes: 1

I believe, with the latest versions of hibernate they have removed support for the <mapping> tag in the configuration file. Instead you can use addAnnotatedClass(<Your domain class>) method defined in the Configuration class. i.e., configuration.addAnnotatedClass(Book.class); in this case.

-Madhu.

Upvotes: 0

Zia
Zia

Reputation: 1011

First implement the Serializable interface in your entity class,

public class Book implements Serializable{
}

Secondly Don't use Configuration with StandardServiceRegistryBuilder, Configuration is considered deprecated, but instead make the bootstrapping as mentioned in the hibernate 5 documentation, for reference go tobelow link,

http://docs.jboss.org/hibernate/orm/5.0/userGuide/en-US/html_single/#bootstrap-native-sessionfactory

or you can modify your code as below to give a try i hope it will work

if (sessionFactory == null) {

        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        configuration.addClass( Book.class ).addResource( "com/openlibrary/model/Book.hbm.xml" );
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(serviceRegistry.build());

    }

Upvotes: 2

Chowdappa
Chowdappa

Reputation: 1620

your book not implemented Serializable. try with this.

public class Book implements Serializable{
}

Upvotes: 1

Related Questions