Partner – Microsoft – NPI (cat= Spring)
announcement - icon

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

And, the Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

You can also ask questions and leave feedback on the Azure Spring Apps GitHub page.

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.

Further reading:

Bootstrapping Hibernate with Spring

A quick and practical guide to integrating Hibernate 5 with Spring.

@Immutable in Hibernate

A quick and practical guide to @Immutable annotation in Hibernate

HibernateException: No Hibernate Session Bound to Thread in Hibernate 3

Discover when "No Hibernate Session Bound to Thread" exception gets thrown and how to deal with it.

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.

Course – LS (cat=Spring)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> THE COURSE
Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.