1. The Problem

This article is going to discuss the org.hibernate.MappingException: Unknown entity issue and solutions, both for Hibernate as well as for a Spring and Hibernate environment.

2. Missing or Invalid @Entity Annotation

The most common cause for the mapping exception is simply an entity class missing the @Entity annotation:

public class Foo implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    public Foo() {
        super();
    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
}

Another possibility is that it may have the wrong type of @Entity annotation:

import org.hibernate.annotations.Entity;

@Entity
public class Foo implements Serializable {
    ...

The deprecated org.hibernate.annotations.Entity is the wrong type of entity to use – what we need is the javax.persistence.Entity:

import javax.persistence.Entity;

@Entity
public class Foo implements Serializable {
    ...

3. MappingException With Spring

The configuration of Hibernate in Spring involves bootstrapping the SessionFactory from annotation scanning, via a LocalSessionFactoryBean:

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(restDataSource());
    ...
    return sessionFactory;
}

This simple configuration of the Session Factory Bean is missing a key ingredient, and a test trying to use the SessionFactory will fail:

...
@Autowired
private SessionFactory sessionFactory;

@Test(expected = MappingException.class)
@Transactional
public void givenEntityIsPersisted_thenException() {
    sessionFactory.getCurrentSession().saveOrUpdate(new Foo());
}

The exception is, as expected – the MappingException: Unknown entity:

org.hibernate.MappingException: Unknown entity: 
com.baeldung.ex.mappingexception.persistence.model.Foo
    at o.h.i.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1141)

Now, there are two solutions to this problem – two ways ways to tell the LocalSessionFactoryBean about the Foo entity class.

We can specify which packages to search for entity classes in the classpath:

sessionFactory.setPackagesToScan(
  new String[] { "com.baeldung.ex.mappingexception.persistence.model" });

Or we can simply register the entity classes directly into the Session Factory:

sessionFactory.setAnnotatedClasses(new Class[] { Foo.class });

With either of these additional configuration lines, the test will now run correctly and pass.

4. MappingException With Hibernate

Let’s now see the error when using just Hibernate:

public class Cause4MappingExceptionIntegrationTest {

    @Test
    public void givenEntityIsPersisted_thenException() throws IOException {
        SessionFactory sessionFactory = configureSessionFactory();

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.saveOrUpdate(new Foo());
        session.getTransaction().commit();
    }

    private SessionFactory configureSessionFactory() throws IOException {
        Configuration configuration = new Configuration();
        InputStream inputStream = this.getClass().getClassLoader().
          getResourceAsStream("hibernate-mysql.properties");
        Properties hibernateProperties = new Properties();
        hibernateProperties.load(inputStream);
        configuration.setProperties(hibernateProperties);

        // configuration.addAnnotatedClass(Foo.class);

        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
          applySettings(configuration.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }
}

The hibernate-mysql.properties file contains the Hibernate configuration properties:

hibernate.connection.username=tutorialuser
hibernate.connection.password=tutorialmy5ql
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.connection.url=jdbc:mysql://localhost:3306/spring_hibernate5_exceptions
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create

Running this test will result in the same mapping exception:

org.hibernate.MappingException: 
  Unknown entity: com.baeldung.ex.mappingexception.persistence.model.Foo
    at o.h.i.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1141)

As it is probably already clear from the example above, what is missing from the configuration is adding the metadata of the entity class – Foo – to the configuration:

configuration.addAnnotatedClass(Foo.class);

This fixes the test – which is now able to persist the Foo entity.

5. Conclusion

This article illustrated why the Unknown entity Mapping Exception may occur, and how to fix the problem when it does, first at the entity level, then with Spring and Hibernate and finally, just with Hibernate alone.

The implementation of all exceptions examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.